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,还 ...
随机推荐
- Java 线程实例 刷碗烧水和倒计时
线程——烧水刷碗和倒计时实例 (一)烧水刷碗 刷碗的同时烧水:下面是碗的程序: 下面是烧水的程序:在水的实现类中,调用了Thread线程,让烧水刷碗同时进行. 注意:刷碗2s一次,烧水10s (二)1 ...
- [SPOJ1811]Longest Common Substring 后缀自动机 最长公共子串
题目链接:http://www.spoj.com/problems/LCS/ 题意如题目,求两个串的最大公共子串LCS. 首先对其中一个字符串A建立SAM,然后用另一个字符串B在上面跑. 用一个变量L ...
- Asp.Net中调用存储过程并返回输出参数
/// <summary> /// 调用存储过程返回参数 /// </summary> /// <param name="orderId">&l ...
- iOS Programming Views :Redrawing and UIScrollView
iOS Programming Views :Redrawing and UIScrollView 1.1 event You are going to see how views are red ...
- oracle DBA笔试题
Unix/Linux题目: 1.如何查看主机CPU.内存.IP和磁盘空间? cat /proc/cpuinfo cat /proc/meminfo ifconfig –a fdisk –l 2.你 ...
- bdflush - 将dirty缓存写回到磁盘的核心守护进程
总览(SYNOPSIS) bdflush [opt] 描述(DESCRIPTION) bdflush 被用来启动核心守护进程将内存中的dirty缓存写到磁盘上.真正清洁工作是一个核心程序完成的. bd ...
- tar (child): lbzip2: Cannot exec: No such file or directory tar (child): Error is not recoverable: exiting now tar: Child returned status 2 tar: Error is not recoverable: exiting now
tar解压bz2格式 报错 解决方法很简单,只要安装bzip2就行了,yum安装的命令如下: yum -y install bzip2 如果是无法联网,可以去官网下载安装包,进一步安装即可
- Tomcat的配置方法(解压版)
Tomcat解压版虽然不用安装,但是死难配!!之前刚学的时候很是郁闷了一阵,Jsp倒还好,但是Servlet死活跑不起来.今天就把你给记下来!! 解压到C:/Tomcat 然后再配置环境变量: 添加三 ...
- tensorflow 学习笔记-- tf.reduce_max、tf.sequence_mask
1.tf.reduce_max函数的作用:计算张量的各个维度上的元素的最大值.例子: import tensorflow as tfmax_value = tf.reduce_max([1, 3, 2 ...
- zay大爷的神仙题目 D1T3-膜你抄
依旧是外链 锦鲤抄 [题目背景] 你在尘世中辗转了千百年 却只让我看你最后一眼 火光描摹容颜燃尽了时间 别留我一人,孑然一身 凋零在梦境里面. ——银临&云の泣<锦鲤抄> [问题描 ...