Many libraries I have found, like Jcrop, do not actually do the cropping, it only creates an image cropping UI. It then depends on the server doing the actual cropping.
How can I make the image cropping client-side by using some HTML5 feature without using any server-side code.
If yes, are there some examples or hints?
Yes, it can be done.
It is based on the new html5 "download" attribute of anchor tags.
The flow should be something like this :
href
attribute for an anchor tag in the domdownload="desired-file-name"
) to thata
element That's it. all the user has to do is click your "download link" and the image will be downloaded to his pc.I'll come back with a demo when I get the chance.
Update
Here's the live demo as I promised. It takes the jsfiddle logo and crops 5px of each margin.
The code looks like this :
Update II
Forgot to mention : of course there is a downside :(.
Because of the same-origin policy that is applied to images too, if you want to access an image's data (through the canvas method
toDataUrl
).So you would still need a server-side proxy that would serve your image as if it were hosted on your domain.
Update III Although I can't provide a live demo for this (for security reasons), here is a php sample code that solves the same-origin policy :
file
proxy.php
:This way, instead of loading the external image direct from it's origin :
You can load it through your proxy :
And here's a sample php code for saving the image data (base64) into an actual image :
file
save-image.php
:All you have to do then is post the image data to this file and it will save the image to disc and return you the existing image filename.
Of course all this might feel a bit complicated, but I wanted to show you that what you're trying to achieve is possible.
If you will still use JCrop, you will need only this php functions to crop the file:
client side:
The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:
Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.
EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the
drawCroppedImage
function with Jcrop.#change-avatar-file
is a file input#change-avatar-file
is a img tag (the target of jcrop) The "key" is FR.onloadend Event https://developer.mozilla.org/en-US/docs/Web/API/FileReader