public class UploadImage {
public static void Resize(String filePath, int height, int width) {
try {
boolean bb=true;
double ratio = 0; //缩放比例
File f = new File(filePath);
BufferedImage bi = ImageIO.read(f);
Image itemp = bi.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
//计算比例
if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
if (bi.getHeight()/height > bi.getWidth()/width) {
ratio = (new Integer(height)).doubleValue() / bi.getHeight();
} else {
ratio = (new Integer(width)).doubleValue() / bi.getWidth();
}
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
itemp = op.filter(bi, null);
if (bb) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//生成的图片在内存里有一个图像缓冲区
Graphics2D g = image.createGraphics();//提供了对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
g.setColor(Color.white);
g.fillRect(0, 0, width, height);//填充一个矩形区域,x、y为起始坐标(即左上角坐标),后面两个参数分别为:w、h,是矩形区域的宽和高.
if (width == itemp.getWidth(null))
g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
else
g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
g.dispose();
itemp = image;
}
ImageIO.write((BufferedImage) itemp, "jpg", f);
}
else
{
bb=true;
if((bi.getHeight() < height) && (bi.getWidth() < width))
{
if((bi.getHeight()<30)&&(bi.getWidth()<30))
{System.out.println("高="+bi.getHeight());
System.out.println("宽="+bi.getWidth());
System.out.println("我是小图片");
ratio=3;
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
itemp = op.filter(bi, null);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.fillRect(0, 0, width, height);
g.setColor(Color.white);
g.drawImage(itemp,(width - itemp.getWidth(null)) / 2, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
//g.drawImage(bi, (width - bi.getWidth(null)) / 2, 0, bi.getWidth(null), bi.getHeight(null), Color.white, null);
g.dispose();
itemp = image;
}
else{
System.out.println("高="+bi.getHeight());
System.out.println("宽="+bi.getWidth());
System.out.println("我是大图片");
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.fillRect(0, 0, width, height);
g.setColor(Color.white);
g.drawImage(bi,(width - bi.getWidth(null)) / 2, (height - bi.getHeight(null)) / 2, bi.getWidth(null), bi.getHeight(null), Color.white, null);
//g.drawImage(bi, (width - bi.getWidth(null)) / 2, 0, bi.getWidth(null), bi.getHeight(null), Color.white, null);
g.dispose();
itemp = image;
}
ImageIO.write((BufferedImage) itemp, "jpg", f);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}