java background transparent -
i have gif image wich contains colored shape, , transparent background
i replace shape's color 1 want (the color palet gif 2 colors : transparent , white in case).
i've created filter wich correctly replace white red (this test)
however i'm encountering issue method imagetobufferedimage, removes transparency , replace black (don't know why).
so i've done far :
import java.awt.color; import java.awt.graphics2d; import java.awt.image; import java.awt.toolkit; import java.awt.image.bufferedimage; import java.awt.image.filteredimagesource; import java.awt.image.imagefilter; import java.awt.image.imageproducer; import java.awt.image.rgbimagefilter; import java.io.file; import javax.imageio.imageio; public class testpng { public static void main(string[] args) throws exception { file in = new file("bg.gif"); bufferedimage source = imageio.read(in); int color = source.getrgb(0, 0); image image = makecolortransparent(source, new color(color), new color(255, 0, 0)); bufferedimage transparent = imagetobufferedimage(image); file out = new file("bg2.gif"); imageio.write(transparent, "gif", out); } private static bufferedimage imagetobufferedimage(image image) { bufferedimage bufferedimage = new bufferedimage(image.getwidth(null), image.getheight(null), bufferedimage.type_int_argb); graphics2d g2 = bufferedimage.creategraphics(); //g2.setbackground(color.blue); g2.clearrect(0, 0, 200, 40); g2.drawimage(image, 0, 0, null); g2.dispose(); return bufferedimage; } public static image makecolortransparent(bufferedimage im, final color search, final color replace) { imagefilter filter = new rgbimagefilter() { public final int filterrgb(int x, int y, int rgb) { if (rgb == search.getrgb()) { return replace.getrgb(); } else { return rgb; } } }; imageproducer ip = new filteredimagesource(im.getsource(), filter); return toolkit.getdefaulttoolkit().createimage(ip); } }
there 3 problems in code:
1) replace
image image = makecolortransparent(source, new color(color), new color(255, 0, 0));
with
image image = makecolortransparent(source, color, new color(255, 0, 0));
and
public static image makecolortransparent(bufferedimage im, final color search, final color replace) { ... if (rgb == search.getrgb()) { ... }
with
public static image makecolortransparent(bufferedimage im, final int search, final color replace) { ... if (rgb == search) { ... }
because reason, source.getrgb(0, 0)
ignores alpha value , becomes white ((255, 255, 255, 0) becomes (255, 255, 255, 255))
2) can't use int color = source.getrgb(0, 0)
, because uses color of first pixel (transparent). should use other code (like asking color in console) find out pixel's color store in int color
3) clearing color of bufferedimage bufferedimage
in imagetobufferedimage(...)
color.black
(default). replace //g2.setbackground(color.blue);
g2.setbackground(new color(0, 0, 0, 0));
or remove g2.clearrect(...);
Comments
Post a Comment