java图片压缩工具类
更新时间:2017年02月04日 11:06:26 作者:Joker_Ye
这篇文章主要为大家详细介绍了java图片压缩工具类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
直接上java图片压缩code:
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
public class ImageProcess {
/**
* 图片
*/
private Image img;
/**
* 宽度
*/
private int width;
/**
* 高度
*/
private int height;
/**
* 文件格式
*/
private String imageFormat;
/**
* 构造函数
* @throws Exception
*/
public ImageProcess(InputStream in,String fileName) throws Exception{
//构造Image对象
img = ImageIO.read(in);
//得到源图宽
width = img.getWidth(null);
//得到源图长
height = img.getHeight(null);
//文件格式
imageFormat = fileName.substring(fileName.lastIndexOf(".")+1);
}
/**
* 按照宽度还是高度进行压缩
* @param w int 最大宽度
* @param h int 最大高度
*/
public byte[] resizeFix(int w, int h) throws IOException {
if (width / height > w / h) {
return resizeByWidth(w);
} else {
return resizeByHeight(h);
}
}
/**
* 以宽度为基准,等比例放缩图片
* @param w int 新宽度
*/
public byte[] resizeByWidth(int w) throws IOException {
int h = (int) (height * w / width);
return resize(w, h);
}
/**
* 以高度为基准,等比例缩放图片
* @param h int 新高度
*/
public byte[] resizeByHeight(int h) throws IOException {
int w = (int) (width * h / height);
return resize(w, h);
}
/**
* 强制压缩/放大图片到固定的大小
* @param w int 新宽度
* @param h int 新高度
*/
public byte[] resize(int w, int h) throws IOException {
// SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );
image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, imageFormat, baos);
return baos.toByteArray();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Java中的SimpleDateFormat的线程安全问题详解
这篇文章主要介绍了Java中的SimpleDateFormat的线程安全问题详解,sonar 是一个代码质量管理工具,SonarQube是一个用于代码质量管理的开放平台,为项目提供可视化报告, 连续追踪项目质量演化过程,需要的朋友可以参考下2024-01-01
使用Spring的ApplicationEvent实现本地事件驱动的实现方法
本文介绍了如何使用Spring的ApplicationEvent实现本地事件驱动,通过自定义事件和监听器,实现模块之间的松耦合,提升代码的可维护性和扩展性。同时还介绍了异步事件和事件传递的相关知识2023-04-04
SpringCloud负载均衡spring-cloud-starter-loadbalancer解读
这篇文章主要介绍了SpringCloud负载均衡spring-cloud-starter-loadbalancer使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2025-03-03
springboot 整合EhCache实现单服务缓存的操作方法
这篇文章主要介绍了springboot 整合EhCache实现单服务缓存的操作方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-07-07
Windows10系统下修改jar中的文件并重新打包成jar文件然后运行的操作步骤
这篇文章主要介绍了Windows10系统下修改jar中的文件并重新打包成jar文件然后运行的操作步骤,文中通过图文结合的形式给大家讲解的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下2024-08-08
JPA如何使用nativequery多表关联查询返回自定义实体类
这篇文章主要介绍了JPA如何使用nativequery多表关联查询返回自定义实体类,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-11-11


最新评论