[英]Constructing Image From 2D Array in Java
I want to create the Image from 2D Array.I used BufferImage concept to construct Image.but there is difference betwwen original Image and constructed Image is displayed by image below 我想从2D数组创建图像。我使用BufferImage概念来构造Image.but原始图像和构造图像之间存在差异由下面的图像显示
I am using the following code 我使用以下代码
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
/** * * @author pratibha */ / ** * * @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();
}
}
You get a ARGB
value from getRGB
and the setRGB
takes a ARGB
value, so doing this is enough: 你得到一个ARGB
从价值getRGB
和setRGB
需要一个ARGB
值,所以这样做是不够的:
bufferImage2.setRGB(x, y, PixelArray[x][y]);
From the API of BufferedImage.getRGB
: 从BufferedImage.getRGB
的API:
Returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and default sRGB colorspace. 返回默认RGB颜色模型(TYPE_INT_ARGB)和默认sRGB颜色空间中的整数像素。
...and from the API of BufferedImage.setRGB
: ...以及来自BufferedImage.setRGB
的API:
Sets a pixel in this BufferedImage to the specified RGB value. 将此BufferedImage中的像素设置为指定的RGB值。 The pixel is assumed to be in the default RGB color model, TYPE_INT_ARGB , and default sRGB color space. 假设像素位于默认的RGB颜色模型TYPE_INT_ARGB和默认的sRGB颜色空间中。
On the other hand I would recommend you do paint the image instead: 另一方面,我建议你改为绘制图像:
Graphics g = bufferImage2.getGraphics();
g.drawImage(g, 0, 0, null);
g.dispose();
Then you wouldn't need to worry about any color model etc. 那你就不用担心任何颜色模型等了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.