Question

I am making an application in which the user will be able to upload an image and then will be able to manipulate the image like zooming and cropping stuff. What I am trying to do is when the user uploads the image if the height is greater than the image I just want to rotate it by 90 degree. I know I can achieve it by using css3 or by using jquery. Is there a way to actually rotate the image not just the presentation I mean change the image itself on client side. I don't want to send the file to server to use image magic or some other libraries as would increase the loading time by adding round trips to the server.

And views on it?

Was it helpful?

Solution

To transform images on client-side you must use HTML5 canvas, but only relatively new browsers will support it.

You'll have to get the image inside a canvas using drawImg(), transform it as you want, convert the canvas to image data and upload it.

// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;

// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Rotate, zoom and crop the image inside the canvas...

// Get the data-URL formatted image.
// This is what you upload to the server and parse as image.
var dataURL = canvas.toDataURL("image/png");

// Upload the image
$.ajax({
  type: "POST",
  url: "/save_image",
  data: { 
   img: dataURL
  }
}

Then decode the image on the server and save it, something like this if you use PHP.

You can use Guillotine to get the data you need from the user to crop/zoom/rotate the image, whether you do it on the browser or on the server (demo).

I hope this helps you to get going.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top