Is there a way to cut image into tiles using Javascript in web browser?
I would like to let user pick one image from the gallery on a web page and then cut that picture in 4 or 6 new tiles, then put those tiles in a table and let the user add some description for each of them.
As I see it now, I could reload tiles from the server after user selects image and number of tiles, but I would like to skip reloading if possible.
Edit:
Regarding KP’s comment on browser level support, I would like to have solution that does not require HTML5 support, if that is possible.
If you are dealing with modern browsers, you could do it with canvas. See this tutorial and look at the “Slicing” section. Basically you can use
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)do chop the original image any way you like it (the
sbased arguments), and place that section anywhere you want (thedbased arguments) in the canvas. If you then want to save a slice, you can use thetoDataUrlmethod to get the base64 of the slice. See this.Keep in mind that the image src url needs to be on the domain the javascript was loaded from, else you’ll taint the canvas. You can get around that by having the server return a base64 representation of the image.
Finally,
toDataUrlon large images can be “slow”, so be ready for that.EDIT — since you can’t rely on canvas, you’d need to use SVG, which being older is supported by more browsers. There are libraries like Raphael.js to help you.