Thursday, 14 May 2015

Building Images On-the-Fly (MemoryImageSource) in Java

The AWT provides a class, MemoryImageSource, that makes it easy to convert an array of data into an image. This is useful if you're building images on-the-fly-drawing the Mandelbrot set, for example. In Listing 17.35, the image is a gradient fill that's built as an array of integers and then converted to an image

Listing 17.35. Working with pixel values.
import java.awt.image.*;
import java.awt.*;
import java.applet.Applet;


public class memory_image extends Applet implements Runnable
{
    Image working;
    Thread the_thread;
    MediaTracker the_tracker;
    int pixels[];
    int max_x, max_y;

    public void start() {
        if (the_thread == null) {
            the_thread = new Thread(this);
            the_thread.start();
        }
    }
    public void stop() {
        the_thread.stop();
    }

    public void run() {
        while (true) {
            repaint();
            try {
                the_thread.sleep(3000);
            } catch(InterruptedException e) {};
        }
    }

    public void init()
    {
        max_x = 256;
        max_y = 256;
        the_tracker = new MediaTracker(this);
        //set up the pixel array that we're going to convert to an image
        pixels = new int[max_x * max_y];
        //set up the new image
        init_pixels();

    }
    public void init_pixels() {
        int x,y,i, j;
        double step;
        //this method does a gradient fill starting with black at the top
        //and going to blue at the bottom
        //step is used to determine how much the color changes between rows
        step = 255.0/max_y;
        i = 0;
        Color c = new Color(0,0,0);
        int ci = c.getRGB();
        j= 0;
        for (y=0;y<max_y;y++) {
            //get a new color for each row. notice that the fastest cycling
            // in the array is x. variable
            c = new Color(0,0,Math.round((float)(j*step)));
            ci = c.getRGB();
            j++;
            for (x=0;x<max_x;x++) {
                pixels[i++]= ci;
            }
        }
        //make the image and use MediaTracker to see when it's
        //done being processed
        working = createImage(new MemoryImageSource
                    (max_x,max_y,pixels,0,max_y));
        the_tracker.addImage(working,0);
    }
    public void paint(Graphics g)
    {
        //if the image is done display it, otherwise let the
        //user know what's going on
        if(the_tracker.checkID(0,true)) {
            g.drawImage(working,0,0,this);
        } else {
            g.drawString("please wait",50,50);
        }
    }
}


After you have an image from the int array, you can use all the other image-processing tools with them.  

No comments:

Post a Comment