/**
* @Title: ImageUtils
* @Description: 调整图片大小
* @author TimBrian
* @since Jan 15, 20192:34:47 PM
* @param srcImgPath 原图片路径
* @param targeImgPath 转换大小后图片路径
* @param width 转换后图片宽度
* @param height 转换后图片高度
* @param format 转换后图片格式
* @throws IOException
*/
public static void resizeImage(String srcImgPath, String targeImgPath, int height, int width,String format) {
File file = new File(srcImgPath);
if (!file.exists()) {
System.out.println("文件不存在");
return ;
}
try (InputStream in = new FileInputStream(file);) {
BufferedImage buff = ImageIO.read(file);
int sourceHeight = buff.getHeight();
int sourceWidth = buff.getWidth();
//获取缩放的基数
float percent = dealwithWH(sourceHeight,sourceWidth, height, width);
//等比例缩放长高
sourceHeight = (int) (sourceHeight * percent);
sourceWidth = (int) (sourceWidth * percent);
Image srcImg = buff;
//生产新的图片
buff = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_INT_RGB);
buff.getGraphics().drawImage(srcImg.getScaledInstance(sourceWidth, sourceHeight, Image.SCALE_SMOOTH), 0, 0, null);
//写出
ImageIO.write(buff, format, new File(targeImgPath));
} catch (IllegalArgumentException e) {
e.printStackTrace();
System.out.println(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
private static float dealwithWH(int sourceHeight, int sourceWidth, int height, int width) {
float percent = 0.00f;
//如果原图片高小于原图片宽,以高为前提,算出比例
if (sourceHeight < sourceWidth) {
percent = (float) height / (float) sourceHeight;
return percent;
}else {
percent = (float) width / (float) sourceWidth;
return percent;
}
}