resize-imagejs
Version:
Resize Image And Convert image to Base64 Or Blob
80 lines (78 loc) • 2.94 kB
JavaScript
function originImageRatio(str) {
return new Promise(function (resolve, reject) {
var image = new Image();
image.src = str;
image.onload = function () {
var width = image.width;
var height = image.height;
var ratio = width / height;
resolve({ ratio: ratio, str: str, originWidth: width, originHeight: height });
};
image.onerror = reject;
});
}
function image2base64(image) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.readAsDataURL(image);
reader.onloadend = function (ev) { var _a; return resolve((_a = ev.target) === null || _a === void 0 ? void 0 : _a.result); };
reader.onerror = reject;
});
}
function getCanvas(image, options) {
var _a;
if (options === void 0) { options = {}; }
var width = options.width, height = options.height;
var canvas = document.createElement('canvas');
var _image = new Image();
_image.src = image;
_image.width = width;
_image.height = height;
canvas.width = width;
canvas.height = height;
(_a = canvas.getContext('2d')) === null || _a === void 0 ? void 0 : _a.drawImage(_image, 0, 0, width, height);
return canvas;
}
function drawImage2base64(image, options) {
if (options === void 0) { options = {}; }
var canvas = getCanvas(image, options);
return canvas.toDataURL('image/jpg', 1);
}
function drawImage2blob(image, options) {
if (options === void 0) { options = {}; }
return new Promise(function (resolve, reject) {
var canvas = getCanvas(image, options);
canvas.toBlob(resolve, 'image/jpg', 1);
});
}
var factoryFun = {
base64: drawImage2base64,
blob: drawImage2blob
};
function resizeImage(image, options) {
if (options === void 0) { options = { type: 'blob' }; }
var width = options.width, height = options.height;
return image2base64(image)
.then(function (res) { return originImageRatio(res); })
.then(function (_a) {
var str = _a.str, ratio = _a.ratio, originWidth = _a.originWidth, originHeight = _a.originHeight;
var _type = 'blob';
if (options.type === 'base64') {
_type = 'base64';
}
if (width && height) {
return factoryFun[_type](str, { width: width, height: height });
}
if (width) {
var _height = width / ratio;
return factoryFun[_type](str, { width: width, height: _height });
}
if (height) {
var _width = height * ratio;
return factoryFun[_type](str, { width: _width, height: height });
}
return factoryFun[_type](str, { width: originWidth, height: originHeight });
});
}
export default resizeImage;
//# sourceMappingURL=resize-imagejs.es5.js.map