图像大小调整在Chrome中有效,但在Firefox中则不然

Image resizing working in Chrome, but not in Firefox

本文关键字:Firefox 但在 有效 调整 Chrome 图像      更新时间:2023-09-26

我的 Angular 1.5 应用程序中有一个函数,如果 base64 编码的图像超过最大大小,可以调整其大小。这个函数在Chrome中效果很好,但在Firefox中它返回一个空字符串,而不是任何base64编码的内容。

我已经把它打包在 Plunker 的 Angular 应用程序中,但这里有相关的功能:

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