Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing Image From 2D Array in Java

Tags:

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

This is My original image

Image After reconstruction

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();
    }
}
like image 522
Sumit Avatar asked Feb 20 '23 13:02

Sumit


1 Answers

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.

like image 109
dacwe Avatar answered Feb 23 '23 00:02

dacwe