devxlogo

How to Construct Images in Memory

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 200×200 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();        anImageIcon.setImage(anImage);        JLabel1.setIcon(anImageIcon);
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist