简体   繁体   中英

How to change the color of some colored pixels on a texture?

I have a black and white texture(800*600 pixels) and I want to change the black pixels to black but quite transparent and change the white pixels to completely transparent.

I've tried using the obvious: take the FloatBuffer with texture data and running a for-loop. Like this for the black pixels:

FloatBuffer data; //The texture data (rgba)
float[] change = new float[]{0, 0, 0, 1}; //Current black color
float[] insert = new float[]{0, 0, 0, 0.5f}; //The new transparent black color

for(int i = 0; i < data.length; i+=4){
    if(data.get(i) == change[0] && data.get(i+1) == change[1] && data.get(i+2) == change[2] && data.get(i+3) == change[3]){
        data.put(i, insert[0]);
        data.put(i+1, insert[1]);
        data.put(i+2, insert[2]);
        data.put(i+3, insert[3]);
    }
}

This turned out to be very very slow, I looked around on the Internet and found this shaders thing. So my question is:

Should I use some sort of shaders code, are there some built in method in opengl/lwjgl or is this a thing I need to do on the cpu and in that case what is the best way?

Sorry for the horrible title and for some spelling problems, but I hope you understand.

There are a few ways you can optimize your existing code to increase its speed:

You could greatly speed this up by not calling data.get() four times in your if statement but instead by getting all the pixel at once and checking that against your black color. This is the biggest bottle neck I see in your code.

Another way to speed it up would just be to ignore the Alpha color data if you can assume that all alpha data for the black pixels is set to 1 or something close to it.

A third way to optimize would be to check the RGB data as integers instead of floats.

Finally, I'm not sure how FloatBuffer and data.get()/put() works, but if you're opening and closing the file each time, that's going to be very slow. Read into memory once, make your changes, and then write the file out only once.

Hope this helps. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM