gpt4 book ai didi

javascript - 图像大小调整在 Chrome 中有效,但在 Firefox 中无效

转载 作者:行者123 更新时间:2023-11-29 15:30:00 25 4
gpt4 key购买 nike

我的 Angular 1.5 应用程序中有一个函数可以在 base64 编码的图像超过最大尺寸时调整其大小。此函数在 Chrome 中运行良好,但在 Firefox 中它返回一个空字符串而不是任何 base64 编码的字符串。

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;
}

最佳答案

您可能需要等到 <img>已加载:

img.onload = function() {
// now your image is ready for use
};

关于javascript - 图像大小调整在 Chrome 中有效,但在 Firefox 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35759809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com