Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need a transparents .PNG?...

Status
Not open for further replies.

TeknomanSlade

Programmer
May 19, 2002
5
0
0
US
...I did. So I did some research and managed to hash
together a rather cool function. I'm really still rather
a newbie when it comes to Java, so I can't bet my life on
how really strong/good/sound this routine is, but it works
great for me, so maybe it'll help someone else out there
who's stuck like I was. Only thing about it is you need
to know your .PNG's size in advance, but...
Code:
public Image Transparent(Image img, int w, int h) {
	Image done;
	MemoryImageSource finale;
        int[] pixels = new int[w * h];
        PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w);
        try { pg.grabPixels(); }
	catch (InterruptedException e) { }
        for (int j = 0; j < h; j++) {
            for (int i = 0; i < w; i++) {
		pixels[j * w + i] = (pixels[j * w + i] == 0xFF27DB27) ? 0x00000000 : pixels[j * w + i];
            }
        }

	finale = new MemoryImageSource(w, h, pixels, 0, w);
	done = createImage(finale);
	return done;
    }
You might want to tweak this a bit if you're going to use
it in your own code. Basically what it does is it converts
the .PNG into an array of pixel data, then seeks out pixels
of a certain color (In this case, a shade of green). If
it finds one, it turns it transparent, otherwise it leaves
it alone. When it's done going through the whole array,
it writes it back to an image and sends it out.

So to use this routine, all you have to do is something
like this...Suppose you've got a .PNG of a ball that's 32
pixels wide and 28 pixels high...
Code:
Image TheBall;
TheBall = getImage(getCodeBase(), &quot;ball.png&quot;);
TheBall = Transparent(TheBall, 32, 28);
And voilah! Instant transparent .PNG-based sprite!

Hopes this helps someone. Later! :)
 
If you create an ImageIcon of the PNG first, you can obtain the width and height in pixels so you don't have to hardcode it:

ImageIcon icon = new ImageIcon(&quot;ball.png&quot;);
TheBall = Transparent(TheBall, icon.getIconWidth(), icon.getIconHeight());

I'm going to file your little trick away for future use. Thanks for sharing it!
 
and how would you go about saving the image back as a png (or any other file type)?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top