java 图片 缩略图_Java实现图片等比例缩略图

@Service

public class ThumbnailService {

public static final int WIDTH  = 100;

public static final int HEIGHT = 100;

//使用类库

public String thumbnail(MultipartFile file,String uploadPath, String realUploadPath){

String imgName = "thum_"+file.getOriginalFilename();

String des = realUploadPath+"/"+imgName;

try {

Thumbnails.of(file.getInputStream()).size(WIDTH,HEIGHT).toFile(des);

}catch (Exception e){

e.printStackTrace();

}

return uploadPath+"/"+imgName;

}

//使用java awt

public String awt(MultipartFile file,String uploadPath, String realUploadPath){

OutputStream os = null;

String imgName = "thum_"+file.getOriginalFilename();

String des = realUploadPath+"/"+imgName;

try {

os = new FileOutputStream(des);

Image image = ImageIO.read(file.getInputStream());

int width = image.getWidth(null);//原图宽

int height = image.getHeight(null);//原图高

int rate1 = width/WIDTH;//缩略图宽比例

int rate2 = height/HEIGHT;//缩略图高比例

int rate = 0;

if(rate1 > rate2){//宽度缩略比例大于高度缩略比例,使用宽度缩略比例

rate = rate1;

}else {

rate = rate2;

}

//计算缩略图最终的宽度和高度

int newWidth = width/rate;

int newHeight = height/rate;

BufferedImage bufferedImage = new BufferedImage(newWidth,newHeight,BufferedImage.TYPE_INT_RGB);

bufferedImage.getGraphics().drawImage(image.getScaledInstance(newWidth,newHeight,image.SCALE_SMOOTH),0,0,null);

String imageType = file.getContentType().substring(file.getContentType().indexOf("/")+1);

ImageIO.write(bufferedImage,imageType,os);

}catch (Exception e){

e.printStackTrace();

}finally {

if(os!=null){

try {

os.close();

}catch (Exception e){

e.printStackTrace();

}

}

}

return uploadPath+"/"+imgName;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值