1

I've read through multiple articles but still have questions left, though what I am trying to implement sounds quite common to me. I have a form which among other input fields allows to attach images.

<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() checks file type, size, name etc. and counts the images uploaded.

I also have a JS function displaying already uploaded images in the canvas (happy to share the code).

Now I am trying to combine both to resize large images before uploading and submit a resized image when the form is submitted. Basically, I want handleFiles() to check the image, resize if needed and substitute the original one to the form. So far I've not been able to make HTML, JS and PHP to work together.

My questions are:

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? 

I am looking for basic resizing in multiples of 2 with JPEG as a target image regardless of source.

Thanks for sharing your experience.

EDIT: I am familiar with the suggested article, however there are seem to be differences: 1) I am trying to load resized image within a form; 2) I am not using Ajax. Here is my HTML:

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

This is my resize() function which uploads file of zero size with the original name:

 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!");
    }

};
user2097141
  • 307
  • 2
  • 4
  • 15
  • [this question](http://stackoverflow.com/questions/18805497/php-resize-image-on-upload#answer-27213444) helped me doing it with PHP. – AymDev Feb 17 '17 at 13:21
  • @AymDev Thanks, AymDev. This is a server-side resizing, similar to my thumbnails code. I may end up with this solution if there is no easy way to resize before uploading, though this will require increasing the default 2MB upload file size. – user2097141 Feb 17 '17 at 13:41
  • what you are asking can be easily researched and there are libraries you can use to help – charlietfl Feb 17 '17 at 16:01
  • Possible duplicate of [HTML5 Pre-resize images before uploading](http://stackoverflow.com/questions/10333971/html5-pre-resize-images-before-uploading) – showdev Feb 17 '17 at 18:43
  • Not a duplicate as the article above 1) Does not upload images as part of form submission, 2) Uses Ajax to upload. Some ideas from the above work well in my server-side processing but no file is uploaded when I try to adapt the code client-side. So far the only available solution on SO used to upload images outside the form. – user2097141 Feb 17 '17 at 19:48
  • Another small comment/question: when drawing image in canvas server-side, I assign img.src AFTER onload=function(){drawImage(...)} to get the image fully loaded. In all examples of resizing this is done BEFORE drawImage(). Any reason? – user2097141 Feb 17 '17 at 21:56

0 Answers0