图片调整大小在Chrome中运行,但在Firefox中无法使用

时间:2016-03-02 22:51:39

标签: javascript angularjs

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

1 个答案:

答案 0 :(得分:1)

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

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