Question

Is there a way to do image color filtering in Google Web Toolkit? Something like Color Matrix Filter using Action Script 3. Here is action script example: AS3:How to change a colored Bitmap's BitmapData to black and white?

Was it helpful?

Solution

For image manipulation in HTML (and therefore GWT) you need to use the canvas element. To my knowledge canvas doesn't give you any shortcuts for applying filters, you will need to get in and modify the pixels by hand. Let's use black-and-white as an example. You need to be sure that the image has already loaded before you can call this method:

public void toBlackAndWhite(Image image)
{
    // Create an off-screen canvas element to do the work.
    Canvas canvas = Canvas.createIfSupported();

    // Do nothing if canvas is not supported.
    if (canvas == null)
        return;

    // Size the canvas to fit the image.
    canvas.setCoordinateSpaceHeight(image.getHeight());
    canvas.setCoordinateSpaceWidth(image.getWidth());

    // Pull the image's underlying DOM element
    ImageElement img = ImageElement.as(image.getElement());

    // The 2D context does all the drawing work on the canvas
    Context2d context = canvas.getContext2d();

    context.drawImage(img, 0, 0); // Now the canvas contains the image.

    // ImageData represents the canvas rgba data as an array of bytes.
    ImageData imageData = context.getImageData(0, 0,
                              image.getWidth(), image.getHeight());

    // Now the real work:
    for (int x = 0; x < imageData.getWidth(); ++x) {
        for (int y = 0; y < imageData.getHeight(); ++y) {
             // RGB values are 0-255
             int average = (imageData.getRedAt(x,y) +
                            imageData.getGreenAt(x,y) +
                            imageData.getBlueAt(x,y)) / 3;

             imageData.setRedAt(average, x,y);
             imageData.setGreenAt(average, x,y);
             imageData.setBlueAt(average, x,y);
         }
    }

    // ImageData is a copy of the data on the canvas, so
    // we need to write it back.
    context.putImageData(imageData,0,0);

    // Now the canvas contains a black and white version
    // of the image. Canvas is a Widget so you could attach
    // it to the page directly if you want. Here we're going
    // to replace the contents of the original image element
    // with a url-encoded version of the canvas contents.
    image.setUrl(canvas.toDataUrl());
}

Not quite as elegant as actionscript but it will do the job. As you can imagine this will chew up a good deal of processor time on larger images, if you need better performance you might consider gwtgl.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top