hal/src/zutil/image/ImageUtil.java

49 lines
1.3 KiB
Java
Raw Normal View History

2008-11-14 16:38:36 +00:00
package zutil.image;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
2008-11-14 16:38:36 +00:00
/**
2010-12-18 00:32:06 +00:00
* This is a static class containing image utility methods
*
2008-11-14 16:38:36 +00:00
* @author Ziver
*/
public class ImageUtil {
/**
2010-12-18 00:38:57 +00:00
* Resizes a BufferedImage
2008-11-14 16:38:36 +00:00
*
2010-12-18 00:39:28 +00:00
* @param source is the image to resize
* @param width is the wanted width
* @param height is the wanted height
* @param keep_aspect is if the aspect ratio of the image should be kept
* @return the resized image
2008-11-14 16:38:36 +00:00
*/
public static BufferedImage scale(BufferedImage source, int width, int height, boolean keep_aspect){
double scale_width = (double)width / source.getWidth();
double scale_height = (double)height / source.getHeight();
2008-11-14 16:38:36 +00:00
// aspect calculation
if(keep_aspect){
if(scale_width * source.getHeight() > height){
scale_width = scale_height;
}else{
scale_height = scale_width;
2008-11-14 16:38:36 +00:00
}
}
BufferedImage tmp = new BufferedImage(
(int)(scale_width * source.getWidth()),
(int)(scale_height * source.getHeight()),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = tmp.createGraphics();
2008-11-14 16:38:36 +00:00
AffineTransform at = AffineTransform.getScaleInstance(scale_width, scale_height);
g2d.drawRenderedImage(source, at);
g2d.dispose();
return tmp;
}
2008-11-14 16:38:36 +00:00
}