简体   繁体   English

图像在上传之前调整大小而不预览javascript

[英]Image resize before upload without preview javascript

I want to avoid uploading big/heavy image files. 我想避免上传大/重图像文件。

I prefer HTML5 FileAPI library for this job. 我更喜欢HTML5 FileAPI库来完成这项工作。

All other functionality is added (upload, re-order, etc.), so I only need the image-resize function. 添加了所有其他功能(上传,重新订购等),因此我只需要图像调整大小功能。

CASE: 案件:

On the page there is an input for multiple files. 在页面上有一个多个文件的输入。

On input change event (when adding files), resize the entered images/files and append them to FormData(), then send the FormData() to PHP script via ajax. 在输入更改事件(添加文件时)时,调整输入的图像/文件的大小并将它们附加到FormData(),然后通过ajax将FormData()发送到PHP脚本。

EXAMPLE: 例:

$('input').on('change',function(){
   var formData = resizeImages(this.files[0]);   
   uploadResizedImages(formData);
});

function resizeImages(files){
   formData = new FormData();

   //For each image, resize it and append to formData
   //resize file part missing....
   formData.append('files[]',this);//Appending to formData (this = currently iterated file)

   return formData;//Return the formData with resized images
}

Anyone? 任何人?

Thanks 谢谢

In my experience you cannot manipulate the image on the client side then upload the manipulated image in tact via a file input in a form. 根据我的经验,您无法在客户端操作图像,然后通过表单中的文件输入上传受控图像。

The way I have done what you are trying to do in the past involves a few steps. 我过去做的事情的方式涉及几个步骤。

  1. Select image using a file input 使用文件输入选择图像
  2. Read the file as a dataURL 将文件作为dataURL读取
  3. Use canvas to manipulate the image as needed 使用画布根据需要操作图像
  4. Export the new image as a dataUrl 将新图像导出为dataUrl
  5. Use ajax to upload the image to the server as a dataURL 使用ajax将映像作为dataURL上载到服务器
  6. Use server side functions to convert the dataUrl to an image and store 使用服务器端函数将dataUrl转换为图像和存储

https://jsfiddle.net/0hmhumL1/ https://jsfiddle.net/0hmhumL1/

function resizeInCanvas(img){
  /////////  3-3 manipulate image
    var perferedWidth = 2700;
  var ratio = perferedWidth / img.width;
  var canvas = $("<canvas>")[0];
  canvas.width = img.width * ratio;
  canvas.height = img.height * ratio;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0,0,canvas.width, canvas.height);
  //////////4. export as dataUrl
  return canvas.toDataURL();
}

When uploading as a dataUrl you increase the size (bandwidth required) of the manipulated image by about 20% so you may not see the savings you are looking for unless you are changing the image size considerably. 当作为dataUrl上传时,您将操纵图像的大小(所需带宽)增加约20%,这样您可能看不到所需的节省,除非您要大幅改变图像大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM