How to scale an image in Java

I programmed my own function, based on other examples:


/**
* Method that scale an image (BufferedImage) into the specified dimensions
* @param sbi Source image
* @param imageType Image type among BufferedImage.TYPE_... constants (example: TYPE_INT_ARGB)
* @param dWidth Image width, in pixels
* @param dHeight Image height, in pixels
* @return Destination image
*/
public static BufferedImage scale(BufferedImage sbi, int imageType, int dWidth, int dHeight) {
BufferedImage dbi = null;
if(sbi != null) {
dbi = new BufferedImage(dWidth, dHeight, imageType);
double wScale = (double) dWidth / (double) sbi.getWidth();
double hScale = (double) dHeight / (double) sbi.getHeight();

AffineTransform at = AffineTransform.getScaleInstance(wScale, hScale);


final AffineTransformOp ato = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
dbi = ato.filter(sbi, dbi);
//last two lines can be substituted by the two following, but results are poorer specially when scaling up:
//Graphics2D g = dbi.createGraphics();
//g.drawRenderedImage(sbi, at);
}
return dbi;
}

External References

Leave a Reply

Your email address will not be published. Required fields are marked *