[英]Two-dimensional RGB array to BufferedImage
I have a custom RGB class: 我有一个自定义的RGB类:
class RGB {
int R, G, B;
}
I make a two-dimensional array of RGB objects representing the image: 我制作了代表图像的RGB对象的二维数组:
RGB[][] image = new RGB[HEIGHT][WIDTH];
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
int pixel = bufferedImage.getRGB(i, j);
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
image[i][j] = new RGB(red, green, blue);
}
}
Now I want to make some changes to this array and save it as a BufferedImage. 现在,我想对此数组进行一些更改,并将其另存为BufferedImage。 Basicly, I can make something like this:
基本上,我可以做这样的事情:
BufferedImage newImage = new BufferedImage(HEIGHT, WIDTH, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
newImage.setRGB(i, j, VALUE);
}
}
But I need to convert RGB fields of each pixel to one integer VALUE, which I don't know how to do. 但是我需要将每个像素的RGB字段转换为一个整数VALUE,我不知道该怎么做。 Or maybe is there a simplier way to do this?
也许有一个更简单的方法可以做到这一点?
Be careful, the function getRGB is bufferedImage.getRGB(x, y), and you do the opposite (x and y inverted). 请注意,函数getRGB是bufferedImage.getRGB(x,y),您执行相反的操作(x和y取反)。
Now you can either work using the Raster or the DataBuffer: 现在,您可以使用Raster或DataBuffer进行工作:
If you don't know the image type and you don't want to duplicate the code, I recommend the Raster, but else, it definitely faster to access and modify the image values using the DataBuffer because you have direct access to the array. 如果您不知道图像类型并且不想重复代码,我建议您使用Raster,否则,使用DataBuffer可以更快地访问和修改图像值,因为您可以直接访问数组。 And TYPE_INT_RGB is not the most practical image format because you have to uncompress/compress the triplet RGB into an int at each time.
TYPE_INT_RGB并不是最实用的图像格式,因为您每次必须将三联体RGB解压缩为一个int。 You can use TYPE_3BYTE_BGR.
您可以使用TYPE_3BYTE_BGR。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.