javascript - 上传前调整图片大小

标签 javascript image-processing

我需要为用户提供一种将照片以 jpeg 格式上传到其网站的方法。但是,照片的原始尺寸非常大,我想让用户在上传前调整大小选项变得非常轻松。似乎我唯一的选择是在通过 Web 服务上传照片之前调整照片大小的客户端应用程序,或者调整图像大小的上传操作的客户端 JavaScript Hook 。第二个选项是非常试探性的,因为我没有 JavaScript 图像大小调整库,并且很难让 JavaScript 运行我当前的调整大小工具 ImageMagick。

我相信这种情况并不少见,我们将不胜感激一些建议或指向执行此操作的网站的指示。

最佳答案

2011 年,我们知道可以使用 File API 和 canvas 来实现。 这目前仅适用于 firefox 和 chrome。 这是一个例子:

var file = YOUR_FILE,
    fileType = file.type,
    reader = new FileReader();

reader.onloadend = function() {
  var image = new Image();
      image.src = reader.result;

  image.onload = function() {
    var maxWidth = 960,
        maxHeight = 960,
        imageWidth = image.width,
        imageHeight = image.height;

    if (imageWidth > imageHeight) {
      if (imageWidth > maxWidth) {
        imageHeight *= maxWidth / imageWidth;
        imageWidth = maxWidth;
      }
    }
    else {
      if (imageHeight > maxHeight) {
        imageWidth *= maxHeight / imageHeight;
        imageHeight = maxHeight;
      }
    }

    var canvas = document.createElement('canvas');
    canvas.width = imageWidth;
    canvas.height = imageHeight;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(this, 0, 0, imageWidth, imageHeight);

    // The resized file ready for upload
    var finalFile = canvas.toDataURL(fileType);
  }
}

reader.readAsDataURL(file);

关于javascript - 上传前调整图片大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/961913/

相关文章:

javascript - 如何更改 div 的不透明度?

javascript - firebase v3 - 谷歌身份验证 "internal-error"

javascript - 在 KENDO UI Multiselect 中选择默认值

javascript - 无法使用 async 和 Foreach 处理 Firebase 获取的值

opencv - 寻找手部图像中的谷点

javascript - 如何简化重复和复杂的js/jquery代码?

python - 将矩形图像调整为正方形,保持比例并用黑色填充背景

iphone - 如何在 iPhone 应用程序中仅缩放图像的特定部分?

java - 是否有任何 java 库可以从图像中读取 vin 号码条形码?

opencv - 如何获得二进制图像中四边形的角