Client-side conversion of rgb-jpg to 8-bit-jpg using Canvas+HTML5

旧巷老猫 提交于 2019-11-27 06:33:15

问题


Many articles shows ways of converting jpeg files to grayscale using canvas+html5 at the client-side. But what I need is to convert an image to 8bit grayscale to reduce its size before uploading to my server.

Is it possible to do it using canvas+html5?


回答1:


The whatwg specification mentions a toBlob method, which is supposed to convert the canvas to a jpeg or png and give you the binary representation. Unfortunately, it isn't widely supported yet.

So all you can do is use getImageData to get an array of the bytes of the raw image data. In this array, every pixel is represented by 4 bytes: red, green, blue and alpha. You can easily calculate the grayscale values from this (gray = (red + green + blue) / 3 * alpha / 255;). But the resulting array will be completely uncompressed, so it will likely be even larger than the original jpeg, even though it only uses 8 bit per pixel. In order to reduce the size, you will have to implement an image compression algorithm yourself. You might consider to use the DEFLATE algorithm used by PNG instead of JPEG encoding - it's a lot easier to implement, doesn't introduce further artifacts because it's lossless, and performs pretty well on 8bit images.

The boilerplate data to turn this compressed data stream into a vialid PNG/JPEG file should be added on the server (when you need it).



来源:https://stackoverflow.com/questions/14174105/client-side-conversion-of-rgb-jpg-to-8-bit-jpg-using-canvashtml5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!