Building an image from a 2D array in Java

I want to create an image from a 2D array. I used the concept of BufferImage to create Image.but there is a difference between the original image and the constructed image in the 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(); } } 
+4
source share
1 answer

You get the ARGB value from getRGB , and setRGB takes the ARGB value, so this is enough:

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

From the BufferedImage.getRGB API:

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

... and from the BufferedImage.setRGB API:

Sets the pixel in this BufferedImage to the specified RGB value. The pixel is assumed to be in the default color model of RGB, TYPE_INT_ARGB and the default sRGB color space.


On the other hand, I would recommend you draw an image instead:

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

Then you do not need to worry about any color model, etc.

+9
source

All Articles