bbb bbb - 1 month ago 14
jQuery Question

How to crop any selected area of an image and save it to the server?

Let me summarize the scenario with a picture:

enter image description here

I am trying to make a feature for setting profile pictures in my site.I want to have a page to show the uploaded image in its original size in an image field but the size of the profile picture should be 200*153 so I want that the users can resize the picure and also drag a frame(the frame size is 200*153) to any area of the resized picture that they want to be their profile picture and when they click on the save button just the area that is in the frame be croped and save that area to the server.

Imagine that these are the HTML codes:

<div style="height:150px;width:200px;position:absolute;border:5px solid yellow;z-index:1001;" id="test1"></div>
<img id="test" src="~/Content/01052013626.jpg"/>


Note that the div is draggable and the image is resizeable.

Thank you.

Answer

You would begin by positioning the image and the div in the same wrapper div. I would do this because it will allow you to use jquery's coordinate functions on the div more easily rather than the image.

Once you have those coordinates, you can take a cropped section of that image specified by the div's dimensions and coordinates and use this tutorial:

http://www.html5canvastutorials.com/tutorials/html5-canvas-image-crop/

To save that section onto an HTML canvas element. The canvas element can be invisible if you like.

Once that is saved, you follow this answer:

How to save a HTML5 Canvas as Image on a server

to save it to the server.