Here you can find the source of createImageFromVisibleComponent(JComponent comp, int cw, int ch)
public static BufferedImage createImageFromVisibleComponent(JComponent comp, int cw, int ch)
//package com.java2s; //License from project: Open Source License import java.awt.Graphics; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.PixelGrabber; import javax.swing.JComponent; public class Main { public static BufferedImage createImageFromVisibleComponent(JComponent comp, int cw, int ch) { BufferedImage retImage = null; if (comp == null) return retImage; try {// ww w . j av a 2 s . c o m GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = genv.getDefaultScreenDevice(); GraphicsConfiguration gc = gd.getDefaultConfiguration(); java.awt.image.ColorModel cm = gc.getColorModel(); boolean hasAlpha = cm.hasAlpha(); if (hasAlpha) { retImage = gc.createCompatibleImage(cw, ch); } else { retImage = new BufferedImage(cw, ch, BufferedImage.TYPE_INT_ARGB); } if (retImage == null) return retImage; Graphics og = retImage.getGraphics(); comp.paint(og); og.dispose(); } catch (Throwable t) { t.printStackTrace(); } return retImage; } /** * Checks for alpha. * * @param image * the image * * @return true, if successful */ public static boolean hasAlpha(Image image) { // If buffered image, the color model is readily available if (image instanceof BufferedImage) { BufferedImage bimage = (BufferedImage) image; return bimage.getColorModel().hasAlpha(); } // Use a pixel grabber to retrieve the image's color model; // grabbing a single pixel is usually sufficient PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false); try { pg.grabPixels(); } catch (InterruptedException e) { } // Get the image's color model ColorModel cm = pg.getColorModel(); return cm.hasAlpha(); } }