客户端使用 Canvas+HTML5 将 rgb-jpg 转换为 8-bit-jpg [英] Client-side conversion of rgb-jpg to 8-bit-jpg using Canvas+HTML5

查看:18
本文介绍了客户端使用 Canvas+HTML5 将 rgb-jpg 转换为 8-bit-jpg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多文章展示了在客户端使用 canvas+html5 将 jpeg 文件转换为灰度的方法.但我需要将图像转换为 8 位灰度以减小其大小,然后再上传到我的服务器.

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.

用canvas+html5可以做到吗?

Is it possible to do it using canvas+html5?

推荐答案

whatwg 规范 提到了一个 toBlob 方法,它应该将画布转换为 jpeg 或 png 并为您提供二进制表示.不幸的是,它还没有得到广泛的支持.

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.

因此,您所能做的就是使用 getImageData 获取原始图像数据的字节数组.在这个数组中,每个像素由 4 个字节表示:红色、绿色、蓝色和 alpha.你可以很容易地计算出灰度值(gray = (red + green + blue)/3 * alpha/255;).但是生成的数组将完全未压缩,因此它可能会比原始 jpeg 更大,即使它每个像素只使用 8 位.为了减小尺寸,您必须自己实现图像压缩算法.您可以考虑使用 PNG 使用的 DEFLATE 算法 而不是 JPEG 编码 - 它更容易实现,不会引入进一步的伪影,因为它是无损的,并且在 8 位图像上表现良好.

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.

应在服务器上添加用于将此压缩数据流转换为有效 PNG/JPEG 文件的样板数据(当您需要时).

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

这篇关于客户端使用 Canvas+HTML5 将 rgb-jpg 转换为 8-bit-jpg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆