tags:

views:

66

answers:

2

I have a single .png image with several icons on it (with transparent areas) and would like to crop individual icons from it. In Java ME it was rather straight-forward, but in BlackBerry I haven't found an equivalent. The code here shows an example with a Bitmap, however doing so paints the transparent areas with white color:

public Bitmap cropImage(Bitmap image, int x, int y, int width, int height) {
    Bitmap result = new Bitmap(width, height);
    Graphics g = new Graphics(result);
    g.drawBitmap(0, 0, width, height, image, x, y);
    return result;
}

I need the same for an EncodedImage to keep the transparency, but Graphics constructor accepts only a Bitmap. Is there any other way to accomplish this? Thank you for any tips.

UPDATE:

Transparency can be preserved if you omit the intermediate Graphics object altogether, and set the ARGB data directly to the newly created Bitmap, like so:

public Bitmap cropImage(Bitmap image, int x, int y, int width, int height) {
    Bitmap result = new Bitmap(width, height);
    int[] argbData = new int[width * height];
    image.getARGB(argbData, 0, width, x, y, width, height);
    result.setARGB(argbData, 0, width, 0, 0, width, height);
    return result;
}
A: 

try to use

g.setGlobalAlpha(0);

before

g.drawBitmap(0, 0, width, height, image, x, y);

or you can use

drawARGB(int[] data, int offset, int scanLength, int x, int y, int width, int height) 

which preserve the alpha in the destination image.

Mahdi Hijazi
Thank you, but could you please provide an example of how the int[] data is obtained in the drawARGB(). Thank you!
Levon
Also, using g.setGlobalAlpha(0) does not work -- it paints the entire area with solid white color.
Levon
+1  A: 

Sorry I didn't try this code but it should give you the idea:

int[] argbData = new int[ width * height ];
image.getARGB(      argbData,
                    0,
                    width
                    x,
                    y,
                    width,
                    height);

Bitmap result = new Bitmap(width, height);
Graphics g = new Graphics(result);
g.drawARGB(argbData , 0, width, 0, 0, width, height);

return result;
Mahdi Hijazi
Thank you for the code, but the result is absolutely the same -- it does not preserve the transparency and draws white pixels where the transparent area should be. As it stands now, I still haven't found a way to crop an image from a larger image while keeping the transparent parts.
Levon
Sorry, I can't help but you can check this http://supportforums.blackberry.com/t5/Java-Development/Transparent-background-for-Bitmap/m-p/233113/message-uid/233113
Mahdi Hijazi
Instead of creating a Graphics object, could you just do a result.setARGB(...) directly into the new Bitmap?
Marc Novakowski
Thank you Marc, it worked when I set it directly into the new Bitmap!
Levon