Convert Image to BufferedImage in Java
In this tutorial, we'll see the easiest way to convert the image type to BufferedImage. The cast (BufferedImage) image; doesn't work, but it is possible to create a new BufferedImage object with the parameters:- Length: img.getWidth()
- Height: image.getHeight()
- Pixels and colors: BufferedImage.TYPE_INT_ARGB.
The conversion is very simple since the BufferedImage inherits from the super Image class.
public static BufferedImage toBufferedImage(Image img)TYPE_INT_ARGB represents an image with 8-bit RGB (RGB) type and supports the alpha rendering and transparency parameter of the class alphaComposite.
{
//if the image is of type BufferedImage
//then we only cast
//because the image passed is of type BufferedImage
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a BufferedImage
BufferedImage bufimage = new BufferedImage(img.getWidth(null),
img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
return bufimage;
}
References:
http://stackoverflow.com/questions/221830/set-bufferedimage-alpha-mask-in-java