Java Image to BufferedImage toBufferedImage(Image image)

Here you can find the source of toBufferedImage(Image image)

Description

to Buffered Image

License

Open Source License

Declaration

public static BufferedImage toBufferedImage(Image image) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.Graphics;
import java.awt.Image;

import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import javax.swing.ImageIcon;

public class Main {
    public static BufferedImage toBufferedImage(Image image) {
        if (image == null)
            return null;

        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }//  w w  w .j ava  2s .co  m

        if (image.getWidth(null) < 0 || image.getHeight(null) < 0) {
            // This code ensures that all the pixels in the image are loaded
            image = new ImageIcon(image).getImage();
        }

        int imgType = hasAlpha(image) ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
        BufferedImage buffImg = new BufferedImage(image.getWidth(null), image.getHeight(null), imgType);
        Graphics g = buffImg.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();

        return buffImg;
    }

    public static boolean hasAlpha(Image image) {
        if (image == null)
            return false;

        if (image instanceof BufferedImage) {
            BufferedImage buffImg = (BufferedImage) image;
            return buffImg.getColorModel().hasAlpha();
        }

        PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
        try {
            pg.grabPixels();
            return pg.getColorModel().hasAlpha();
        } catch (InterruptedException e) {

        }

        return true;
    }
}

Related

  1. toBufferedImage(Image i)
  2. toBufferedImage(Image image)
  3. toBufferedImage(Image image)
  4. toBufferedImage(Image image)
  5. toBufferedImage(Image image)
  6. toBufferedImage(Image image)
  7. toBufferedImage(Image image)
  8. toBufferedImage(Image image)
  9. toBufferedImage(Image image)