src/utils/cropImage.js
/**
* Crops an image to get a square picture
* @param {String} imageUrl Uri of an image
* @param {Integer} widthScalated Width of the image
* @param {Integer} heightScalated Height of the image
* @return {String} Base64 uri of a transformed image
* @private
*/
export function cropImage(imageUrl, widthScalated, heightScalated) {
return new Promise((resolve) => {
if (!window) {
resolve(imageUrl);
}
let image = new Image();
image.onload = function() {
let canvas = document.createElement('canvas');
canvas.width = Math.min(this.width, widthScalated);
canvas.height = Math.min(this.height, heightScalated);
let sx = 0, sy = 0, dx = 0, dy = 0;
let sWidth = this.width;
let sHeight = this.width;
let dWidth = Math.min(this.width, widthScalated);
let dHeight = Math.min(this.height, heightScalated);
if (this.height > this.width) {
sy = (this.height - this.width) / 2;
} else if (this.height < this.width) {
sx = (this.width - this.height) / 2;
sWidth = sHeight = this.height;
}
canvas.getContext('2d').drawImage(this,
sx, sy,
sWidth,
sHeight,
dx, dy,
dWidth, dHeight);
let base64Url = canvas.toDataURL('image/png');
image = null;
canvas = null;
resolve(base64Url);
};
image.src = imageUrl;
});
}