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

查看:201
本文介绍了使用Canvas + HTML5将客户端rgb-jpg转换为8位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。您可以轻松地从此计算灰度值(灰色=(红色+绿色+蓝色)/ 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.

应该在服务器上添加将此压缩数据流转换为vialid 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位jpg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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