如何使用 java 从 RGB 像素值创建有效图像
How to create valid image from RGB pixel values using java
我有一个包含 RGB 值的二维数组。我需要根据这些像素值创建有效图像并保存。我在下面给出了二维数组。我想在我的项目中实现这部分,所以请帮助我。谢谢。
int[] pixels = new int[imageSize * 3];
int k = 0;
for(int i=0; i<height; i++)
{
for(int j=0; j<width; j++)
{
if(k<imageSize*3)
{
pixels[k] = r[i][j];
pixels[k+1] = g[i][j];
pixels[k+2] = b[i][j];
}
k = k+3;
}
}
您可以构建一个 BufferedImage
of type BufferedImage.TYPE_INT_RGB
。此类型将颜色表示为 int
,其中:
- 第 3 个字节 (16-23) 为红色,
- 第 2 个字节 (8-15) 为绿色且
- 第一个字节 (7-0) 为蓝色。
可以得到像素RGB
值如下:
int rgb = red;
rgb = (rgb << 8) + green;
rgb = (rgb << 8) + blue;
示例 (Ideone full example code):
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int rgb = r[y][x];
rgb = (rgb << 8) + g[y][x];
rgb = (rgb << 8) + b[y][x];
image.setRGB(x, y, rgb);
}
}
File outputFile = new File("/output.bmp");
ImageIO.write(image, "bmp", outputFile);
我有一个包含 RGB 值的二维数组。我需要根据这些像素值创建有效图像并保存。我在下面给出了二维数组。我想在我的项目中实现这部分,所以请帮助我。谢谢。
int[] pixels = new int[imageSize * 3];
int k = 0;
for(int i=0; i<height; i++)
{
for(int j=0; j<width; j++)
{
if(k<imageSize*3)
{
pixels[k] = r[i][j];
pixels[k+1] = g[i][j];
pixels[k+2] = b[i][j];
}
k = k+3;
}
}
您可以构建一个 BufferedImage
of type BufferedImage.TYPE_INT_RGB
。此类型将颜色表示为 int
,其中:
- 第 3 个字节 (16-23) 为红色,
- 第 2 个字节 (8-15) 为绿色且
- 第一个字节 (7-0) 为蓝色。
可以得到像素RGB
值如下:
int rgb = red;
rgb = (rgb << 8) + green;
rgb = (rgb << 8) + blue;
示例 (Ideone full example code):
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int rgb = r[y][x];
rgb = (rgb << 8) + g[y][x];
rgb = (rgb << 8) + b[y][x];
image.setRGB(x, y, rgb);
}
}
File outputFile = new File("/output.bmp");
ImageIO.write(image, "bmp", outputFile);