views:

516

answers:

1

Hello,

is there any possiblity in J2ME to convert an image (loaded from a png file with alpha) to a new transparent grayscale image?

Until now I only got the rgb values, but not the alpha.

Thanks.

Edit: yes, it should be 32 bit grayscale.

+1  A: 

I found the solution and here is the code:

    public Image getGrayScaleImage() {
    int[] rgbData = new int[getWidth() * getHeight()];
    image.getRGB(rgbData, 0, getWidth(), 0, 0, getWidth(), getHeight());
    for (int x = 0; x < getWidth() * getHeight(); x++) {
        rgbData[x] = getGrayScale(rgbData[x]);
    }
    Image grayImage = Image.createRGBImage(rgbData, getWidth(), getHeight(), true);
    return grayImage;
}

private int getGrayScale(int c) {
    int[] p = new int[4];
    p[0] = (int) ((c & 0xFF000000) >>> 24); // Opacity level
    p[1] = (int) ((c & 0x00FF0000) >>> 16); // Red level
    p[2] = (int) ((c & 0x0000FF00) >>> 8); // Green level
    p[3] = (int) (c & 0x000000FF); // Blue level

    int nc = p[1] / 3 + p[2] / 3 + p[3] / 3;
    // a little bit brighter
    nc = nc / 2 + 127;

    p[1] = nc;
    p[2] = nc;
    p[3] = nc;

    int gc = (p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]);
    return gc;
}

getRGB returns the color value that also includes the alpha channel. So I only had to change each value in the array and create an image from that.

I found a helpful document in the nokia forum: MIDP 2.0: Working with Pixels and drawRGB()

André