如何将.gif转换为字节[] []? [英] How do you turn a .gif into a byte[][]?
问题描述
我正在使用具有方法的API
I am using an API that has a method
public void setImage(byte[][] newImage)
API参考中给出的唯一信息是
The only information given to be in the API Reference is
此图像的格式是一个简单的原始 2D数组
个字节。每个字节代表从黑色(0)$开始的灰色阴影c $ c>到
white(255)
。索引 2D数组
时, Y轴
首先, X轴
其次,例如image [y] [x]。
参数值未在内部克隆。不必要的共享,请在调用此方法之前克隆图像数据。
"The format of this image is a simple raw 2D array
of bytes. Every byte represents shade of gray from black (0)
to white (255)
. When indexing the 2D array
, Y axis
goes first, X axis
goes second, e.g. image[y][x].
Parameter value is not cloned internally. To avoid unwanted sharing, clone the image data before calling this method."
我应该将.gif图像传递给此方法,但无法确定我如何将.gif转换为 byte [] []数组
。
I am supposed to be passing a .gif image to this method but can not figure out for the life of me how to turn a .gif into a byte[][] array
.
任何帮助都会很棒!谢谢。
Any help would be great! Thanks.
推荐答案
有多种方法可以将颜色转换为灰度,但是最简单的方法是对红色,灰色和蓝色值进行平均: / p>
There's various ways to convert color to grayscale but the simplest is to average the red, grean and blue values like this:
BufferedImage image = ImageIO.read(new File([your gif]));
int[][] imageBytes = new int[image.getHeight()][image.getWidth()];
for (int y = 0; y < image.getHeight(); y++)
{
for (int x = 0; x < image.getWidth(); x++)
{
Color color = new Color(image.getRGB(x, y));
imageBytes[y][x] = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
}
}
注意,我使用了 int
数组是因为(如我之前评论的)API声明了 setImage
方法存在一个基本问题。 Java中的 byte
是带符号的,因此代表最小值-128,最大值127,因此不能使用0-255的值。
Note, I have used an int
array because (as I previously commented) there's a fundimental problem with the API that declared the setImage
method. A byte
in Java is signed and therefore represents a minimum of -128 and a maximum value of 127, so cannot be used to values 0 - 255.
这篇关于如何将.gif转换为字节[] []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!