Sistema de blogs Diarium
Universidad de Salamanca
Pablo Gallardo's Blog
My professional web log about IT, Cybersecurity & Project Management
 

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;
}

References

Sources:
How to resize image in Java“, by A4L, stackoverflow.
Image Scale in Java“, by Nirale

pmgallardo

About pmgallardo

I studied Computer Science at University of Salamanca. Since then, I have been working first as developer and then as SAP consutant. This blog is about problems I dealt when using computers, and more important, the solutions I found. Whenever I am on an issue and suddenlly I have a flash that leads me to a solution, I document my discoveries in a post.

, , , , , ,

No comments yet.

Leave a Reply


*

Política de privacidad
Studii Salmantini. Campus de excelencia internacional