1.服务端压缩
- 1.hutool ,它是个java工具库,官网地址:https://hutool.cn/docs/#/
图片工具部分有使用示例,缩放比例设置为0.5,压缩后的图片是原图的一半(宽度、高度)
ImgUtil.scale(
FileUtil.file("c:/index_bg1.jpg"),
FileUtil.file("c:/index_bg1_result.jpg"),
0.5f//缩放比例
);
- 2.Thumbnails,它是google使用的开源的工具类,可在不改变原图大小情况下,压缩原图的质量,来减少图片大小,github地址:https://github.com/coobird/thumbnailator
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
Thumbnails.of("c:/index_bg1.jpg") //原图文件的路径
.scale(1f) //scale是指定图片的大小,值在0到1之间,1f就是原图大小
.outputQuality(0.5f) //图片的质量,值也是在0到1,越接近于1质量越好
.toFile("c:/index_bg1_result.jpg"); //压缩后文件的路径
这个工具无法正确压缩出png格式的图片,因为png本身就是一种无损的图片格式,而jpg是一种压缩的图片格式,因此可以把png格式输出为 jpg 来达到压缩目的
Thumbnails.of("c:/index_bg2.png")
.scale(1f)
.outputQuality(0.5f)
.outputFormat("jpg")
.toFile("c:/index_bg2_result.jpg");
来看看2张图片压缩后的大小与效果
左边是原图,右边是压缩后的,图片大小差了一半,基本上没有失真
2.客户端压缩
- 1.插件1:使用开源组件 imgResize,github地址:https://github.com/CommanderXL/imgResize
import canvasResize from 'canvas-resize'
canvasResize(img, {
crop: false,
quality: 0.9,
rotate: 0,
callback(baseStr) {
console.log(baseStr.length)
}
})
- 2.插件2:compression.js,github地址:https://github.com/fengyuanchen/compressorjs/blob/master/README.md
<script type="text/javascript" src="compression.js"></script>
<P>当前压缩比例 0.5</P>
<div id="img">上传图片</div>
<br>
<p id="zz"></p>
<img id="jg" src="">
<script type="text/javascript">
window.onload = function() {
var dd = new compression({
domId:"img", // 上传图片的Dom 目前只支持id;
type:"jpg", // 压缩后保存图片的类型,目前支持 jpeg , png 参数:jpeg png
fidelity: .5, // 压缩比例 (0,1]
imgFile:function(base64){
// alert(base64) // 压缩好的回调
$("#zz").text("以下为压缩后的图片");
$("#jg").attr("src",base64);
}
})
}
</script>