fastman3-dfyjapp-jsbridge
Version:
a jsbridge module for dfyj app
63 lines (57 loc) • 2.09 kB
JavaScript
function _processBase64(img, maxWidth, maxHeight, callback) {
// Max size for thumbnail
if (typeof maxWidth === 'undefined') maxWidth = 500;
if (typeof maxHeight === 'undefined') maxHeight = 500;
// Create and initialize two canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var canvasCopy = document.createElement("canvas");
var copyContext = canvasCopy.getContext("2d");
// // Create original image
// var img = new Image();
// img.src = base64;
// Determine new ratio based on max size
var ratio = 1;
if (img.width > maxWidth) ratio = maxWidth / img.width;else if (img.height > maxHeight) ratio = maxHeight / img.height;
// Draw original image in second canvas
canvasCopy.width = img.width;
canvasCopy.height = img.height;
copyContext.drawImage(img, 0, 0);
// Copy and resize second canvas to first canvas
canvas.width = img.width * ratio;
canvas.height = img.height * ratio;
ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
var resizeDataURL = canvas.toDataURL();
if (typeof callback == "function") {
callback(resizeDataURL);
}
}
function _loadImage(imgSrc, maxWidth, maxHeight, callback) {
// Create original image
var image = new Image();
image.src = imgSrc;
if (image.complete) {
_processBase64(image, maxWidth, maxHeight, callback);
image.onload = function () {};
} else {
image.onload = function () {
_processBase64(image, maxWidth, maxHeight, callback);
// clear onLoad, IE behaves erratically with animated gifs otherwise
image.onload = function () {};
};
image.onerror = function () {
alert("Could not load image.");
};
}
}
/**
* 将base64转换为规定的尺寸
* @param {*} base64 DataURI
* @param {*} maxWidth 最大宽度
* @param {*} maxHeight 最大高度
* @param {*} callback 异步回调
*/
function asyncResizeBase64(base64, maxWidth, maxHeight, callback) {
_loadImage(base64, maxWidth, maxHeight, callback);
}
export { asyncResizeBase64 };