开发者

Faster way to set a (PNG) bitmap color instead of pixel by pixel

开发者_Python百科

I have some png files that I am applying a color to. The color changes depending on a user selection. I change the color via 3 RGB values set from another method. The png files are a random shape with full transparency outside the shape. I don't want to modify the transparency, only the RGB value. Currently, I'm setting the RGB values pixel by pixel (see code below).

I've come to realize this is incredibly slow and possibly just not efficient enough do in an application. Is there a better way I could do this?

Here is what I am currently doing. You can see that the pixel array is enormous for an image that takes up a decent part of the screen:

public void foo(Component component, ComponentColor compColor, int userColor) {
    int h = component.getImages().getHeight();
    int w = component.getImages().getWidth();
    mBitmap = component.getImages().createScaledBitmap(component.getImages(), w, h, true);

    int[] pixels = new int[h * w];

    //Get all the pixels from the image
    mBitmap[index].getPixels(pixels, 0, w, 0, 0, w, h);

    //Modify the pixel array to the color the user selected
    pixels = changeColor(compColor, pixels);

    //Set the image to use the new pixel array
    mBitmap[index].setPixels(pixels, 0, w, 0, 0, w, h);
}

public int[] changeColor(ComponentColor compColor, int[] pixels) {
    int red = compColor.getRed();
    int green = compColor.getGreen();
    int blue = compColor.getBlue();
    int alpha;

    for (int i=0; i < pixels.length; i++) {
        alpha = Color.alpha(pixels[i]);
        if (alpha != 0) {
            pixels[i] = Color.argb(alpha, red, green, blue);
        }
    }
    return pixels;
}


Have you looked at the functions available in Bitmap? Something like extractAlpha sounds like it might be useful. You an also look at the way functions like that are implemented in Android to see how you could adapt it to your particular case, if it doesn't exactly meet your needs.


The answer that worked for me was a write up Square did here Transparent jpegs

They provide a faster code snippet for doing this exact thing. I tried extractAlpha and it didn't work but Square's solution did. Just modify their solution to instead modify the color bit and not the alpha bit.

i.e.

pixels[x] = (pixels[x] & 0xFF000000) | (color & 0x00FFFFFF);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜