Converting an int array into an image

How can a int array be converted into an Image?
Well, that depends on the format in which the image is stored inside the int array. I will assume that each pixel is stored into a single int in aRGB format (1st byte – alpha, 2nd byte – red, 3rd byte – green, 4th byte – blue), and that the array contains the pixel values row by row (meaning that first the array contains the upper most row of the image, then the 2nd row, then the 3rd etc.) If you have it stored in a different format, convert to this one first.
Here’s code that does the trick:

/**
 * Creates an Image object from the given array of pixels.
 *
 * @param pixels The pixels array.
 * @param width The width of the Image.
 * @param height The height of the Image.
 *
 * @return An Image object representing the image stored
 * in the given int array.
 */

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

How can an image be displayed as fast as possible
Well, obviously we are drawing images using one of the various Graphics.drawImage() methods, so apparently there’s nothing we can do to speed up the drawing… The tricky part here is to know that images created with an ImageProducer such as ones we’ve created in the first question (and ones you usually create with the getImage() methods) draw much slower than images created with the Component.createImage(width,height) method. So how do we obtain such a fast drawing image? Simple – let’s draw the slow drawing image on the fast drawing image once and then draw the fast drawing image on the screen every time.
Here’s code that does this:


/**
 * Creates a new offscreen Image that will contain the same
 * data as the given image. The given Image must be preloaded.
 *
 * @param img The source image.
 * @param component Any onscreen component (one that has a peer).
 *
 * @return An offscreen copy of the given image.
 */
 
public static Image toOffscreenImage(Image img, Component comp){
  int width = img.getWidth(null);
  int height = img.getHeight(null);
  Image offScreenImage = comp.createImage(width,height);
  offScreenImage.getGraphics().drawImage(img,0,0,null);
  return offScreenImage;
}

It is important that the Component you give to the above method is onscreen (has a peer), meaning it’s inside a toplevel container (Window, Frame, Dialog) whose setVisible(true) method has been called.