2007.11.29 21:29

Java Image to Buffered Image

public BufferedImage toBufferedImage(Image input) {
    if (input instanceof BufferedImage)
        return (BufferedImage) input;
    if (input instanceof VolatileImage) 
        return ((VolatileImage)input).getSnapshot();
    //too lazy to use MediaTracker directly:
    ImageIcon imageIcon = new ImageIcon(input);
    if (imageIcon.getImageLoadStatus() != MediaTracker.COMPLETE)
        throw new IllegalArgumentException("Can't load image");
    input = imageIcon.getImage();
    int w = input.getWidth(null);
    int h = input.getHeight(null);
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    GraphicsConfiguration gc = gd.getDefaultConfiguration();
    BufferedImage output = gc.createCompatibleImage(w,h);
    //what about transparency? This code assumes it's OPAQUE,
    //but you can interrogate the image's source for its ColorModel
    Graphics2D g = output.createGraphics();
    g.drawImage(input, 0, 0, null);
    return output;
Trackback 0 Comment 1