Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn an array of pixels into an Image object with Java's ImageIO?

I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code:

public Image getImageFromArray(int[] pixels, int width, int height) {     MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width);     Toolkit tk = Toolkit.getDefaultToolkit();     return tk.createImage(mis); } 

Is it possible to achieve the same result using classes from the ImageIO package(s) so I don't have to use the AWT Toolkit?

Toolkit.getDefaultToolkit() does not seem to be 100% reliable and will sometimes throw an AWTError, whereas the ImageIO classes should always be available, which is why I'm interested in changing my method.

like image 467
Chris Carruthers Avatar asked Sep 24 '08 00:09

Chris Carruthers


People also ask

What does getRGB return?

getRGB. Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, from a portion of the image data. Color conversion takes place if the default model does not match the image ColorModel .

What is a pixel array?

Description. The pixels[] array contains the values for all the pixels in the display window. These values are of the color datatype. This array is defined by the size of the display window.

How do I change the pixels of an image in Java?

Setting the ARGB values − Create a Color object bypassing the new RGB values as parameters. Get the pixel value from the color object using the getRGB() method of the Color class. Set the new pixel value to the image by passing the x and y positions along with the new pixel value to the setRGB() method.

How do you read pixels on a picture?

Find the image file in your Finder, right click the image and select Get Info. A pop-up window will open with the dimensions of your image displaying in the More Info section. The dimensions show the pixel height and width of your photo.


1 Answers

You can create the image without using ImageIO. Just create a BufferedImage using an image type matching the contents of the pixel array.

public static Image getImageFromArray(int[] pixels, int width, int height) {             BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);             WritableRaster raster = (WritableRaster) image.getData();             raster.setPixels(0,0,width,height,pixels);             return image;         } 

When working with the PixelGrabber, don't forget to extract the RGBA info from the pixel array before calling getImageFromArray. There's an example of this in the handlepixelmethod in the PixelGrabber javadoc. Once you do that, make sure the image type in the BufferedImage constructor to BufferedImage.TYPE_INT_ARGB.

like image 121
Brendan Cashman Avatar answered Oct 02 '22 22:10

Brendan Cashman