How to scale a BufferedImage
suggest change/**
* Resizes an image using a Graphics2D object backed by a BufferedImage.
* @param srcImg - source image to scale
* @param w - desired width
* @param h - desired height
* @return - the new resized image
*/
private BufferedImage getScaledImage(Image srcImg, int w, int h){
// TRANSLUCENT is Transparency.TRANSLUCENT, whose value is 3.
// The constructor reads that argument as an image type, and 3 is TYPE_INT_ARGB_PRE,
// a premultiplied ARGB image. It is not TYPE_INT_ARGB (2). The alpha channel is still present.
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
// Drawing context for the image created above.
Graphics2D g2 = resizedImg.createGraphics();
//This could be changed, Cf. http://stackoverflow.com/documentation/java/5482/creating-images-programmatically/19498/specifying-image-rendering-quality
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
//Finally draw the source image in the Graphics2D with the desired size.
g2.drawImage(srcImg, 0, 0, w, h, null);
//Disposes of this graphics context and releases any system resources that it is using
g2.dispose();
//Return the image used to create the Graphics2D
return resizedImg;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents