java - Save JFrame as image with transparent background -


i'm sorry know there lot of questions couldn't find solution. tried different things can't background transparent. here test code:

public class pngs extends jpanel {  public void paint(graphics g) {     image img = createimage();     g.drawimage(img, 0, 0, this); }  public static bufferedimage getscreenshot(         component component) {      bufferedimage image = new bufferedimage(             component.getwidth(),             component.getheight(),             bufferedimage.type_int_rgb     ); // call component's paint method, using     // graphics object of image.     component.paint(image.getgraphics());     return image; }  private static image createimage() {     bufferedimage img = null;     try {          img = imageio.read(new file("oneimg.png"));     } catch (ioexception e) {     }     return img; }  public static void main(string[] args) {     jframe frame = new jframe();     frame.getcontentpane().add(new pngs());     frame.setundecorated(true);     frame.getcontentpane().setbackground(new color(1.0f, 1.0f, 1.0f, 0.5f));     frame.setdefaultcloseoperation(jframe.exit_on_close);     frame.setsize(512, 512);     frame.setvisible(true);     try { //saves image         // retrieve image         bufferedimage bi = getscreenshot(frame.getcontentpane());         file outputfile = new file("saved.png");         imageio.write(bi, "png", outputfile);     } catch (ioexception e) {     } }  } 

i tried set 4th argument of color constructor 0 transparent black background. when set 0.5f it's not transparent @ all.

what problem?

use bufferedimage.type_int_argb instead of bufferedimage.type_int_rgb.
way: use code create proper screenshots:

public static bufferedimage getscreenshot(component component) throws awtexception {     graphicsenvironment ge = graphicsenvironment.getlocalgraphicsenvironment();     graphicsdevice gd = ge.getdefaultscreendevice();     robot robot = new robot(gd);     rectangle bounds = new rectangle(component.getlocationonscreen(), component.getsize());     return robot.createscreencapture(bounds); }  

Comments