简体   繁体   中英

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

这是我原来的形象

图像重建后

I am using the following code

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

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]);

From the API of BufferedImage.getRGB :

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

...and from the API of BufferedImage.setRGB :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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