Added resizeImage()

paul/schema_breaking_changes
Emmanuel ROHEE 2014-08-21 13:35:04 +02:00
parent d12a7c3939
commit efe5aa6464
1 changed files with 86 additions and 1 deletions

View File

@ -22,7 +22,7 @@
angular.module('mUtilities', [])
.service('mUtilities', ['$q', function ($q) {
/*
* Gets the size of an image
* Get the size of an image
* @param {File} imageFile the file containing the image
* @returns {promise} A promise that will be resolved by an object with 2 members:
* width & height
@ -50,4 +50,89 @@ angular.module('mUtilities', [])
return deferred.promise;
};
/*
* Resize the image to fit in a square of the side maxSize.
* The aspect ratio is kept. The returned image data uses JPEG compression.
* Source: http://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
* @param {File} imageFile the file containing the image
* @param {Integer} maxSize the max side size
* @returns {promise} A promise that will be resolved by a Blob object containing
* the resized image data
*/
this.resizeImage = function(imageFile, maxSize) {
var self = this;
var deferred = $q.defer();
var canvas = document.createElement("canvas");
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function(e) {
img.src = e.target.result;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = maxSize;
var MAX_HEIGHT = maxSize;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataUrl = canvas.toDataURL("image/jpeg", 0.7);
deferred.resolve(self.dataURItoBlob(dataUrl));
};
reader.onerror = function(e) {
deferred.reject(e);
};
reader.readAsDataURL(imageFile);
return deferred.promise;
};
/*
* Convert a dataURI string to a blob
* Source: http://stackoverflow.com/a/17682951
* @param {String} dataURI the dataURI can be a base64 encoded string or an URL encoded string.
* @returns {Blob} the blob
*/
this.dataURItoBlob = function(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
return new Blob([ab],{type: mimeString});
};
}]);