Mark Mark - 3 months ago 23x
Javascript Question

Possible to resize an image (client side) on an html form before upload?

I have a standard html input form that includes a field for uploading a file (image).

I unfortunatly cannot edit the backend php that processes the file, but I need to resize the images to a certain size.

I was thinking I could pull off this trick by having the images resized by jquery or alternative client side methods, on the form, before the actual submission to the PHP form.

Is this possible? Anyone know of a good method?



You can use the new FileReader to let the user select an image from their local file system.

Then you can use canvas to resize the image as needed.

enter image description here

This code lets the user select a local image file.

The image will be scaled to half size on the client side.

<!doctype html>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<title>Image preview example</title>
<script type="text/javascript">
oFReader = new FileReader(), rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;

oFReader.onload = function (oFREvent) {

  var img=new Image();
      var canvas=document.createElement("canvas");
      var ctx=canvas.getContext("2d");
      document.getElementById("uploadPreview").src = canvas.toDataURL();

function loadImageFile() {
  if (document.getElementById("uploadImage").files.length === 0) { return; }
  var oFile = document.getElementById("uploadImage").files[0];
  if (!rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; }

<body onload="loadImageFile();">
  <form name="uploadForm">
          <td><img id="originalImg"/></td>
          <td><img id="uploadPreview"/></td>
          <td><input id="uploadImage" type="file" name="myPhoto" onchange="loadImageFile();" /></td>

Modern browsers support the FileReader (but for IE you need 10+).