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

后端 未结 1 981
陌清茗
陌清茗 2020-12-10 21:20

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

相关标签:
1条回答
  • 2020-12-10 21:59

    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).

    0 讨论(0)
提交回复
热议问题