Skip to content
Advertisement

Use HTML5 to resize an image before upload

I have found a few different posts and even questions on stackoverflow answering this question. I am basically implementing this same thing as this post.

So here is my issue. When I upload the photo, I also need to submit the rest of the form. Here is my html:

JavaScript

Previously, I did not need to resize the image, so my javascript looked like this:

JavaScript

This all worked great… now that I need to resize the images… how can I replace the image in the form so that the resized one is posted and not the uploaded image?

JavaScript

I’ve thought about moving the file input out of the form and having a hidden input in the form that I set the value of to the value of the resized image… But I’m wondering if I can just replace the image that is already in the form.

Advertisement

Answer

Here is what I ended up doing and it worked great.

First I moved the file input outside of the form so that it is not submitted:

JavaScript

Then I changed the uploadPhotos function to handle only the resizing:

JavaScript

As you can see I’m using canvas.toDataURL('image/jpeg'); to change the resized image into a dataUrl adn then I call the function dataURLToBlob(dataUrl); to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:

JavaScript

Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement