用Java从2D数组构造图像 [英] Constructing Image From 2D Array in Java
问题描述
我想从2D数组创建图像,我使用BufferImage概念构造Image.但是原始图像与下面显示的图像之间存在差异
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
我正在使用以下代码
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
/**** @作者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();
}
}
推荐答案
您从 getRGB
获得了 ARGB
值,而 setRGB
接受了 ARGB
值,所以这样做就足够了:
You get a ARGB
value from getRGB
and the setRGB
takes a ARGB
value, so doing this is enough:
bufferImage2.setRGB(x, y, PixelArray[x][y]);
来自 BufferedImage.getRGB
:
在默认RGB颜色模型(TYPE_INT_ARGB)和默认sRGB颜色空间中返回整数像素.
Returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and default sRGB colorspace.
...and from the API of BufferedImage.setRGB
:
将此BufferedImage中的像素设置为指定的RGB值.假定像素为默认RGB颜色模型,TYPE_INT_ARGB 和默认sRGB颜色空间.
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.
另一方面,我建议您改为绘制图像:
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.
这篇关于用Java从2D数组构造图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!