在上传表单之前重新调整图像大小

时间:2017-02-17 13:17:05

标签: javascript forms image upload resize

我已阅读过多篇文章,但仍然有疑问,尽管我试图实现的内容听起来很常见。 我有一个表单,其中包括其他输入字段允许附加图像。

<form action="add2.php" method="post" enctype="multipart/form-data" id="addform">

... some input fields

<input name="uploadfile3" type="file" id="i3_file" onchange="handleFiles('i3_file')" />

<input type="submit" name="submit" value="Submit listing" class="submit"/>
</form>

handleFiles()检查文件类型,大小,名称等,并计算上传的图像。

我还有一个JS功能,在画布上显示已经上传的图像(很高兴分享代码)。

现在我尝试将两者结合起来在上传之前调整大图像的大小,并在提交表单时提交调整大小的图像。基本上,我希望handleFiles()检查图像,如果需要调整大小,并将原始的替换为表单。到目前为止,我还没能使HTML,JS和PHP协同工作。

我的问题是:

1) Is it possible in JS/PHP only, without Ajax? 
2) Is it possible within the same form? My attempts to use FormData to append a field with a resized file resulted in no image uploaded (upload is handled in PHP using $_FILES[][]). 
3) Where is the temporary image stored while being resized but before been uploaded? 
4) Would it be better to use canvas.toBlob with callback function (which in my view can only add a filed to the form) or canvas.toDataURL and then convert to blob or not use canvas at all? 

我正在寻找以2的倍数进行基本调整大小,将JPEG作为目标图像,无论其来源如何。

感谢您分享您的经验。

编辑:我对建议的文章很熟悉,但似乎存在差异:1)我试图在表单中加载已调整大小的图像; 2)我没有使用Ajax。 这是我的HTML:

<input name="uploadfile" type="file" id="i1_file" onchange="resize('i1_file', 'uploadfile', 'addform')"  />

这是我的resize()函数,它使用原始名称上传零大小的文件:

 function resize(inputid,  inputname,  formid)
{
    //Check if File interface is supported
    if (window.File && window.FileReader && window.FileList && window.Blob)
    {
        var inpFiles = document.getElementById(inputid);
        var file = inpFiles.files[0];
        //var inpFiles = document.getElementById('i_file');
        //get the file size and file type from file input field
        var fsize = file.size;
        var ftype = file.type;
        var fname = file.name;
        var c = 3 - inputid.substr(1,1);
        if (c == 0) c = 'no';


        if (ftype.indexOf("jpeg") < 0 && ftype.indexOf("png") < 0)
              {
                  alert(ftype + " is not a valid image type!");
              } else if (fsize == 0)
                   {
                     alert("Invalid file size: " + fsize +" bites\nTry another image");
                   } else if
                       ((fsize > 1048576) && (fsize < 4194304)) //Resize if file size more than 1 mb (1048576) but less than 4 mb
                       {
                          alert("Resizing " + fsize +" bites\n of " + fname);
                           var dataurl = null;
                           // create <img> element
                           var img = document.createElement("img");
                           var reader = new FileReader();  
                           reader.onload = function(e) {
                            img.src = e.target.result;

                           // Once you have the image preview in an <img> element, you can draw this image in a <canvas> element to pre-process the file.

                            var canvas = document.createElement("mycanvas");
                            var context = canvas.getContext('2d'); 
                            context.drawImage(img, 0, 0);

                                  var width = file.naturalWidth;
                                  var height = file.naturalHeight;
                                  if ((width > 1024) && (width > height)) 
                                  {
                                    var new_width = 1024;
                                    var ratio = new_width / width;
                                    var new_height = Math.round(height * ratio);
                                    }  
                                    else if (height > 768)
                                     {
                                        var new_height = 768;
                                        var ratio = new_height / height;
                                        var new_width = Math.round(width * ratio);
                                     }
                                    else
                                    {
                                       var new_width = width;
                                       var new_height = height;
                                    }
                                    document.write("new_height: " + new_height + "<br />");
                                    canvas.width = new_width;
                                    canvas.height = new_height;
                                    var context = canvas.getContext('2d'); 
                                    context.drawImage(img,0,0,new_width, new_height);
                                    // save canvas as dataUrl
                                    dataurl = canvas.toDataURL("image/jpeg", 0.8);

                                    var fd = new FormData(document.getElementById(formid));
                                    // convert dataUrl into blob
                                    var blobBin = atob(dataurl.split(',')[1]);
                                    var array = [];
                                    for(var i = 0; i < blobBin.length; i++) {
                                    array.push(blobBin.charCodeAt(i));
                                    }
                                    var newfile = new Blob([new Uint8Array(array)], {type: 'image/jpeg', name: fname});

                                    fd.append(inputid, newfile); // blob file

                              } //onload

                              reader.readAsDataURL(file);


                       }else if (fsize > 4194304)
                             {
                               alert("Too big: " + fsize +" bites\nResize or use another image");
                              }else
                                  {
                                    alert("Good: " + fsize +" bites\nType: " + ftype +"\nYou can add " + c + " more below");
                                  }
    }else{
        alert("Please upgrade your browser ,\n cannot handle files!");
    }

};

0 个答案:

没有答案
相关问题