Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a thumbnail image after adding an image inside an input type="file" in a form and submitting them both on the same form

I have a form which allows the user to upload a picture. After the user has submitted the form, I'd like to generate on the front-end a thumbnail for each picture and then store it on server.

For security reason it's not possible to alter the value of a file input field, so how could I send to server some thumbnails images generated on the front-end in js?

Is it possible on front-end to generate a thumbnail from the image set in the input file field before form submit? And then submitting both at same time?

like image 620
Alessandro Incarnati Avatar asked May 11 '13 19:05

Alessandro Incarnati


People also ask

How do you add a thumbnail to a file?

To add a new thumbnail image for a selected file, first click the Add button as shown below in the image. 2. A new window will then appear and show a list that will let you select up to three files at once. Click Select File to select the image file you wish to assign as the thumbnail image file.

How do you add a thumbnail to an image in HTML?

Use the border property to create thumbnail images. Wrap an anchor around the image to use it as a link. Hover over the image and click on it to see the effect.


Video Answer


2 Answers

I found This simpler yet powerful tutorial. It simply creates an img element and, using the fileReader object, assigns its source attribute as the value of the form input

function previewFile() {    var preview = document.querySelector('img');    var file    = document.querySelector('input[type=file]').files[0];    var reader  = new FileReader();      reader.onloadend = function () {      preview.src = reader.result;    }      if (file) {      reader.readAsDataURL(file);    } else {      preview.src = "";    }  }
<input type="file" onchange="previewFile()"><br>  <img src="" height="200" alt="Image preview...">
like image 189
Cedric Ipkiss Avatar answered Sep 19 '22 03:09

Cedric Ipkiss


After a better search online I found the answer to my question.

It is possible to combine canvas together with the File API.

Try to upload any picture in the demo below and see that a new generated thumbnail will appear on the right side of the form.

DEMO: http://jsfiddle.net/a_incarnati/fua75hpv/

function handleImage(e){     var reader = new FileReader();     reader.onload = function(event){         var img = new Image();         img.onload = function(){             canvas.width = img.width;             canvas.height = img.height;             ctx.drawImage(img,0,0);         }         img.src = event.target.result;     }     reader.readAsDataURL(e.target.files[0]);      } 

A good answer has been given by DerekR to this question:

How to upload image into HTML5 canvas

like image 41
Alessandro Incarnati Avatar answered Sep 22 '22 03:09

Alessandro Incarnati