gpt4 book ai didi

java - 在 Java 中从二维数组构建图像

转载 作者:搜寻专家 更新时间:2023-11-01 01:36:28 24 4
gpt4 key购买 nike

我想从二维数组创建图像。我使用 BufferImage 概念来构造图像。但是原始图像和构造图像之间存在差异,如下图所示

This is My original image

Image After reconstruction

我正在使用下面的代码

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

/** * * @author pratibha */

public class ConstructImage{
int[][] PixelArray;
public ConstructImage(){
try{

BufferedImage bufferimage=ImageIO.read(new File("D:/q.jpg"));
int height=bufferimage.getHeight();
int width=bufferimage.getWidth();
PixelArray=new int[width][height];
for(int i=0;i<width;i++){
for(int j=0;j<height;j++){
PixelArray[i][j]=bufferimage.getRGB(i, j);
}
}
///////create Image from this PixelArray
BufferedImage bufferImage2=new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);

for(int y=0;y<height;y++){
for(int x=0;x<width;x++){
int Pixel=PixelArray[x][y]<<16 | PixelArray[x][y] << 8 | PixelArray[x][y];
bufferImage2.setRGB(x, y,Pixel);
}


}

File outputfile = new File("D:\\saved.jpg");
ImageIO.write(bufferImage2, "jpg", outputfile);


}
catch(Exception ee){
ee.printStackTrace();
}
}

public static void main(String args[]){
ConstructImage c=new ConstructImage();
}
}

最佳答案

您从 getRGB 获得了一个 ARGB 值,而 setRGB 获得了一个 ARGB 值,所以这样做是够了:

bufferImage2.setRGB(x, y, PixelArray[x][y]);

来自 BufferedImage.getRGB 的 API :

Returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and default sRGB colorspace.

...以及来自 BufferedImage.setRGB 的 API :

Sets a pixel in this BufferedImage to the specified RGB value. The pixel is assumed to be in the default RGB color model, TYPE_INT_ARGB, and default sRGB color space.


另一方面,我建议您改为绘制图像:

Graphics g = bufferImage2.getGraphics();
g.drawImage(g, 0, 0, null);
g.dispose();

那么你就不需要担心任何颜色模型等。

关于java - 在 Java 中从二维数组构建图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11897297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com