3
我的Angular 1.5應用程序中有一個函數,如果尺寸超過最大尺寸,它會調整base64編碼圖片的大小。該功能在Chrome中非常適用,但在Firefox中,它返回一個空字符串,而不是任何base64編碼的。在Chrome瀏覽器中調整圖片大小,但不在Firefox中
I've got it packaged up in an Angular app in Plunker here,但這裏的相關功能:
// Image resizing
$scope.resizeImage = function(base64Data, maxWidth, maxHeight) {
img = document.createElement('img');
img.src = base64Data;
height = img.height;
width = img.width;
if (width > maxWidth) {
ratio = maxWidth/width; // get ratio for scaling image
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if (height > maxHeight) {
ratio = maxHeight/height; // get ratio for scaling image
width = width * ratio; // Reset width to match scaled image
height = height * ratio; // Reset height to match scaled image
}
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// We set the dimensions at the wanted size.
canvas.width = width;
canvas.height = height;
// We resize the image with the canvas method drawImage();
ctx.drawImage(img, 0, 0, width, height);
var dataURI = canvas.toDataURL();
return dataURI;
}