Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Sep 2, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

How to Construct Images in Memory

There are many simple images (stripes, hue gradients, fractals, and the like) that can easily be constructed in memory via code. To do so, you need a one-dimensional array to contain pixel data.

Once you have your array of pixels, you create an instance of java.awt.image.MemoryImageSource with the pixel array and image size as parameters. Then, you call java.awt.Toolkit.createImage(ImageProducer producer) to create the image in memory.

The following method constructs, and returns 200x200 image representing a fade from black to blue along the X axis and a fade from black to red along the Y axis:

Image createBlackBlueRedFade()
    int width = 200;
    int height = 200;
    int pix[] = new int[width * height];
    int index = 0;
    for (int y = 0; y < height; y++) 
        int red = (y * 255) / (height - 1);
        for (int x = 0; x < width; x++) 
            int blue = (x * 255) / (width - 1);
            pix[index++] = (255 << 24) | (red << 16) | blue;
    return createImage(new MemoryImageSource(width, height, pix, 0, width));

Now, you can use the Image object returned from the method and show it somewhere. For example, if you have a javax.swing.JLabel called JLabel1, youcan set its icon to display the image you just constructed:


        Image anImage = createBlackBlueRedFade();
        javax.swing.ImageIcon anImageIcon = new javax.swing.ImageIcon();


Behrouz Fallahi
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date