繁体   English   中英

用Java构建二维数组图像

[英]Constructing Image From 2D Array in Java

我想从2D数组创建图像。我使用BufferImage概念来构造Image.but原始图像和构造图像之间存在差异由下面的图像显示

这是我原来的形象

图像重建后

我使用以下代码

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();
    }
}

你得到一个ARGB从价值getRGBsetRGB需要一个ARGB值,所以这样做是不够的:

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

BufferedImage.getRGB的API:

返回默认RGB颜色模型(TYPE_INT_ARGB)和默认sRGB颜色空间中的整数像素。

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

将此BufferedImage中的像素设置为指定的RGB值。 假设像素位于默认的RGB颜色模型TYPE_INT_ARGB和默认的sRGB颜色空间中。


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

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

那你就不用担心任何颜色模型等了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM