Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...