java对图片进行压缩和resize缩放的方法
更新时间:2017年07月31日 10:49:16 作者:xixicat
本篇文章主要介绍了java对图片进行压缩和resize调整的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
序
这里展示一下如何对图片进行压缩和resize。分享给大家,具体如下:
压缩
public static boolean compress(String src,String to, float quality) {
boolean rs = true;
// Build param
JPEGEncodeParam param = null;
// Build encoder
File destination = new File(to);
FileOutputStream os = null;
try {
BufferedImage image = ImageIO.read(new File(src));
param = JPEGCodec.getDefaultJPEGEncodeParam(image);
param.setQuality(quality, false);
os = FileUtils.openOutputStream(destination);
JPEGImageEncoder encoder;
if (param != null) {
encoder = JPEGCodec.createJPEGEncoder(os, param);
} else {
return false;
}
encoder.encode(image);
} catch(Exception e){
e.printStackTrace();
rs = false;
}finally {
IOUtils.closeQuietly(os);
}
return rs;
}
resize
public static boolean resize(String src,String to,int newWidth,int newHeight) {
try {
File srcFile = new File(src);
File toFile = new File(to);
BufferedImage img = ImageIO.read(srcFile);
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = new BufferedImage(newWidth, newHeight, img.getType());
Graphics2D g = dimg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, newWidth, newHeight, 0, 0, w, h, null);
g.dispose();
ImageIO.write(dimg, "jpg", toFile);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
java中 String和StringBuffer的区别实例详解
这篇文章主要介绍了java中 String和StringBuffer的区别实例详解的相关资料,一个小的例子,来测试String和StringBuffer在时间和空间使用上的差别,需要的朋友可以参考下2017-04-04
Spring Boot 2 Thymeleaf服务器端表单验证实现详解
这篇文章主要介绍了Spring Boot 2 Thymeleaf服务器端表单验证实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2019-11-11
关于Spring自定义XML schema 扩展的问题(Spring面试高频题)
今天给大家分享一道spring高频率面试题关于Spring自定义XML schema 扩展的问题,今天以spring整合dubbo的实例给大家详细讲解下,感兴趣的朋友跟随小编一起看看吧2021-05-05
mybatis注解动态sql注入map和list方式(防sql注入攻击)
这篇文章主要介绍了mybatis注解动态sql注入map和list方式(防sql注入攻击),具有很好的参考价值,希望对大家有所帮助。2021-11-11


最新评论