java服务器图片压缩的几种方式及效率比较
以下是测试了三种图片压缩方式,通过测试发现使用jdk的ImageIO压缩时间更短,使用Google的thumbnailator更简单,但是thumbnailator在GitHub上的源码已经停止维护了。
1、Google的thumbnailator
pom.xml中引入依赖
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
测试源码:
/**
* @Title: ThumbnailatorUtil
* @Package: com.test.image
* @Description: google Thumbnailator 测试
* @Author: monkjavaer
* @Data: 2019/2/22 14:07
* @Version: V1.0
*/
public class ThumbnailatorUtil { public static void main(String[] args) {
try {
long start = System.nanoTime();
compressPic();
long end = System.nanoTime();
System.out.println("压缩时间:"+(end-start)*0.000000001+"s");
} catch (IOException e) {
e.printStackTrace();
}
} /**
* scale: 按比例
* outputQuality:输出的图片质量,范围:0.0~1.0,1为最高质量。注意使用该方法时输出的图片格式必须为jpg
* @throws IOException
*/
public static void compressPic() throws IOException {
// Thumbnails.of("E:\\3.png")
Thumbnails.of("E:\\154.jpg")
.scale(1f)
.outputQuality(0.25f)
.toFile("E:\\1.jpg");
} }
输出:压缩时间:0.5615769580000001s
2、Java原生ImageIO实现:
/**
* @Title: ImageIOUtil
* @Package: com.test.image
* @Description: ImageIO test
* @Author: monkjavaer
* @Data: 2019/2/22 16:37
* @Version: V1.0
*/
public class ImageIOUtil { public static void main(String[] args) throws IOException {
long start = System.nanoTime();
compressPic("E:\\154.jpg", "E:\\1.jpg", 0.25f);
long end = System.nanoTime();
System.out.println("压缩时间:" + (end - start) * 0.000000001 + "s");
} public static void compressPic(String srcFilePath, String descFilePath, Float quality) throws IOException {
File input = new File(srcFilePath);
BufferedImage image = ImageIO.read(input); // 指定写图片的方式为 jpg
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); // 先指定Output,才能调用writer.write方法
File output = new File(descFilePath);
OutputStream out = new FileOutputStream(output);
ImageOutputStream ios = ImageIO.createImageOutputStream(out);
writer.setOutput(ios); ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()){
// 指定压缩方式为MODE_EXPLICIT
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// 压缩程度,参数qality是取值0~1范围内
param.setCompressionQuality(quality);
}
// 调用write方法,向输入流写图片
writer.write(null, new IIOImage(image, null, null), param); out.close();
ios.close();
writer.dispose();
}
}
输出:压缩时间:0.44548557000000005s
3、com.sun.image.codec.jpeg.JPEGCodec实现
测试代码:
public class JPEGCodecUtil {
public static void main(String[] args) throws IOException {
long start = System.nanoTime();
compressPic(new File("E:\\154.jpg"), new File("E:\\1.jpg"), 1920, 0.25f);
long end = System.nanoTime();
System.out.println("压缩时间:" + (end - start) * 0.000000001 + "s");
}
/**
* 缩放图片(压缩图片质量,改变图片尺寸)
* 若原图宽度小于新宽度,则宽度不变!
* @param newWidth 新的宽度
* @param quality 图片质量参数 0.7f 相当于70%质量
* 2015年12月11日
*/
public static void compressPic(File originalFile, File resizedFile,
int newWidth, float quality) throws IOException {
if (quality > 1) {
throw new IllegalArgumentException(
"Quality has to be between 0 and 1");
}
ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
Image i = ii.getImage();
Image resizedImage = null;
int iWidth = i.getWidth(null);
int iHeight = i.getHeight(null);
if(iWidth < newWidth){
newWidth = iWidth;
}
if (iWidth > iHeight) {
resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight)
/ iWidth, Image.SCALE_SMOOTH);
} else {
resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight,
newWidth, Image.SCALE_SMOOTH);
}
// This code ensures that all the pixels in the image are loaded.
Image temp = new ImageIcon(resizedImage).getImage();
// Create the buffered image.
BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
// Copy image to buffered image.
Graphics g = bufferedImage.createGraphics();
// Clear background and paint the image.
g.setColor(Color.white);
g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
g.drawImage(temp, 0, 0, null);
g.dispose();
// Soften.
float softenFactor = 0.05f;
float[] softenArray = { 0, softenFactor, 0, softenFactor,
1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 };
Kernel kernel = new Kernel(3, 3, softenArray);
ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
bufferedImage = cOp.filter(bufferedImage, null);
// Write the jpeg to a file.
FileOutputStream out = new FileOutputStream(resizedFile);
// Encodes image as a JPEG data stream
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder
.getDefaultJPEGEncodeParam(bufferedImage);
param.setQuality(quality, true);
encoder.setJPEGEncodeParam(param);
encoder.encode(bufferedImage);
} // Example usage
}
输出:压缩时间:0.52596054s
java服务器图片压缩的几种方式及效率比较的更多相关文章
- Java中图片压缩处理
原文http://cuisuqiang.iteye.com/blog/2045855 整理文档,搜刮出一个Java做图片压缩的代码,稍微整理精简一下做下分享. 首先,要压缩的图片格式不能说动态图片,你 ...
- Java中HashMap遍历的两种方式
Java中HashMap遍历的两种方式 转]Java中HashMap遍历的两种方式原文地址: http://www.javaweb.cc/language/java/032291.shtml 第一种: ...
- JAVA中集合输出的四种方式
在JAVA中Collection输出有四种方式,分别如下: 一) Iterator输出. 该方式适用于Collection的所有子类. public class Hello { public stat ...
- java读取XML文件的四种方式
java读取XML文件的四种方式 Xml代码 <?xml version="1.0" encoding="GB2312"?> <RESULT& ...
- java中数组复制的两种方式
在java中数组复制有两种方式: 一:System.arraycopy(原数组,开始copy的下标,存放copy内容的数组,开始存放的下标,需要copy的长度); 这个方法需要先创建一个空的存放cop ...
- java实现图片压缩
java实现图片压缩 package Test; import java.awt.Image; import java.awt.image.BufferedImage; import java.io. ...
- java动态获取WebService的两种方式(复杂参数类型)
java动态获取WebService的两种方式(复杂参数类型) 第一种: @Override public OrderSearchListRes searchOrderList(Order_Fligh ...
- java 实现md5加密的三种方式与解密
java 实现md5加密的三种方式 CreateTime--2018年5月31日15点04分 Author:Marydon 一.解密 说明:截止文章发布,Java没有实现解密,但是已有网站可以免费 ...
- Python:实现图片裁剪的两种方式——Pillow和OpenCV
原文:https://blog.csdn.net/hfutdog/article/details/82351549 在这篇文章里我们聊一下Python实现图片裁剪的两种方式,一种利用了Pillow,还 ...
随机推荐
- 好用的SqlParamterList
public class SqlParameterList : List<SqlParameter> { #region Properties /// <summary> // ...
- AJPFX:学习JAVA程序员两个必会的冒泡和选择排序
* 数组排序(冒泡排序)* * 冒泡排序: 相邻元素两两比较,大的往后放,第一次完毕,最大值出现在了最大索引处* * 选择排序 : 从0索引开始,依次和后面元素比较,小的往前放,第一次完毕,最小值出现 ...
- 策略模式--Java篇
策略模式(Strategy):它定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户. 下面将以商场打折为例子,说明策略模式.商场收银如何促销,用打折还是 ...
- pycharm一些快捷键(不定时添加)
ctrl + shift + - 缩减多级菜单 ctrl + shifit + + 展开多级菜单 ctrl + shift + F8 删除多个断点 两个项目比较 ---选中要比较的项目---右键找 ...
- "CSRF token missing or incorrect."的解决方法.
现象: Forbidden (403)CSRF verification failed. Request aborted.HelpReason given for failure:CSRF token ...
- PAT甲级考前整理(2019年3月备考)之三,持续更新中.....
PAT甲级考前整理一:https://www.cnblogs.com/jlyg/p/7525244.html,主要讲了131题的易错题及坑点 PAT甲级考前整理二:https://www.cnblog ...
- Farseer.net轻量级开源框架说明及链接索引
Farseer.net是什么? 基于.net framework 4 开发的一系列解决方案. 完全开源在GitHub中托管.并发布到NuGet中. Farseer.Net由最初的关系数据库ORM框架后 ...
- 移动端使用页尾文字使用绝对定位遇到input框会飘起来的处理方案
如下版权信息的样式在遇到input框的时候会跟随输入框其后 优雅的解决方式:(定位遇上键盘飘窗解决) mounted里面写上:var originalHeight=document.documentE ...
- 前端phtooshop基础
1.图片理论基础 2.使用Adobe FireWorks切图和S0VG的处理 可以单独生成一个图片的切图 选择多个切图部分生成CSS Sprite,甚至CSS和html都生成了对应的文件. 3.Ph ...
- mathAge.call(btn) 函数call 改变函数内 this #js
mathAge.call(btn) 函数call 改变函数内 this