图片等比例缩放

package com.bancool.common;


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


import javax.imageio.ImageIO;


import sun.awt.image.codec.JPEGImageEncoderImpl;
/**
 * 图片工具类
 * @author xin
 *
 */
public class ImageTool {
/**
* 图片等比例缩放
* @param src 地址
* @param maxWidth 最大宽度
* @param maxHeight 最大高度
* @return
*/
public static boolean change(String src,int maxWidth,int maxHeight){
int width,height;
double scale;//比例
try {
File file = new File(src);
Image image = ImageIO.read(file);
//等比例运算
width=image.getWidth(null);
height=image.getHeight(null);
scale=(width+0.1)/(height+0.1);
if(scale>=(maxWidth+0.1)/(maxHeight+0.1)&&width>maxWidth){
width=maxWidth;
height=(int)(maxWidth/scale);
}
if(scale<(maxWidth+0.1)/(maxHeight+0.1)&&height>maxHeight){
height=maxHeight;
width=(int)(maxHeight*scale);
}
//创建图像
BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
bi.getGraphics().drawImage(image,0,0,width, height, null);
//转码输出
FileOutputStream out = new FileOutputStream(file);
JPEGImageEncoderImpl encoder = new JPEGImageEncoderImpl(out);
encoder.encode(bi);
out.close();
} catch (IOException e) {


}
return true;
}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值