Create Image of Static (like on TV)

Description: This function returns an image of width x height that essentially contains nothing but black and white pixels (like "snow" on TV). It requires java.util.Random, java.awt.*, java.awt.image.MemoryImageSource. It is good for showing you how you can manipulate pixels to create an image.
Tested Platform: Java SE 1.7, Windows 7
Language: Java
// Return a static image of width and height
public static Image getStaticImage(int w, int h) {
    int[] pixels = new int[w * h];
    Random rand = new Random();
    int index = 0;
    	
    // Loop through the pixels of our new image.
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            int random = rand.nextInt(2);
            int r = 0;
            int g = 0;
            int b = 0;
    			
            // If random is one, make it white
            // Otherwise it is a black pixel
            if (random == 1) {
                r = 255;
                g = 255;
                b = 255;
            }
    		    
            // Assemble the pixels (here the 255 is your alpha)
            pixels[index++] = (255 << 24) | (r << 16) | (g << 8) | b;
        }
    }
    	
    return Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w,h,pixels,0,w));
}

Submitted: February 25, 2013

Return to the snippets listing