|
@@ -0,0 +1,81 @@
|
|
1
|
+package com.community.huiju.common;
|
|
2
|
+
|
|
3
|
+import net.coobird.thumbnailator.Thumbnails;
|
|
4
|
+import org.slf4j.Logger;
|
|
5
|
+import org.slf4j.LoggerFactory;
|
|
6
|
+
|
|
7
|
+import java.io.ByteArrayInputStream;
|
|
8
|
+import java.io.ByteArrayOutputStream;
|
|
9
|
+
|
|
10
|
+/**
|
|
11
|
+ * 图片压缩Utils
|
|
12
|
+ *
|
|
13
|
+ * @author worstEzreal
|
|
14
|
+ * @version V1.1.0
|
|
15
|
+ * @date 2018/3/12
|
|
16
|
+ */
|
|
17
|
+public class PicUtils {
|
|
18
|
+
|
|
19
|
+ private static Logger logger = LoggerFactory.getLogger(PicUtils.class);
|
|
20
|
+
|
|
21
|
+ /*public static void main(String[] args) throws IOException {
|
|
22
|
+ byte[] bytes = FileUtils.readFileToByteArray(new File("C:\\Users\\DELL\\Pictures\\timg.jpg"));
|
|
23
|
+ long l = System.currentTimeMillis();
|
|
24
|
+ bytes = PicUtils.compressPicForScale(bytes, 20, "x");// 图片小于300kb
|
|
25
|
+ System.out.println(System.currentTimeMillis() - l);
|
|
26
|
+ FileUtils.writeByteArrayToFile(new File("C:\\Users\\DELL\\Pictures\\timg.jpg"), bytes);
|
|
27
|
+ }*/
|
|
28
|
+
|
|
29
|
+ /**
|
|
30
|
+ * 根据指定大小压缩图片
|
|
31
|
+ *
|
|
32
|
+ * @param imageBytes 源图片字节数组
|
|
33
|
+ * @param desFileSize 指定图片大小,单位kb
|
|
34
|
+ * @param imageId 影像编号
|
|
35
|
+ * @return 压缩质量后的图片字节数组
|
|
36
|
+ */
|
|
37
|
+ public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize, String imageId) {
|
|
38
|
+ if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {
|
|
39
|
+ return imageBytes;
|
|
40
|
+ }
|
|
41
|
+ long srcSize = imageBytes.length;
|
|
42
|
+ double accuracy = getAccuracy(srcSize / 1024);
|
|
43
|
+ try {
|
|
44
|
+ while (imageBytes.length > desFileSize * 1024) {
|
|
45
|
+ ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
|
|
46
|
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
|
|
47
|
+ Thumbnails.of(inputStream)
|
|
48
|
+ .scale(accuracy)
|
|
49
|
+ .outputQuality(accuracy)
|
|
50
|
+ .toOutputStream(outputStream);
|
|
51
|
+ imageBytes = outputStream.toByteArray();
|
|
52
|
+ }
|
|
53
|
+ logger.info("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb",
|
|
54
|
+ imageId, srcSize / 1024, imageBytes.length / 1024);
|
|
55
|
+ } catch (Exception e) {
|
|
56
|
+ logger.error("【图片压缩】msg=图片压缩失败!", e);
|
|
57
|
+ }
|
|
58
|
+ return imageBytes;
|
|
59
|
+ }
|
|
60
|
+
|
|
61
|
+ /**
|
|
62
|
+ * 自动调节精度(经验数值)
|
|
63
|
+ *
|
|
64
|
+ * @param size 源图片大小
|
|
65
|
+ * @return 图片压缩质量比
|
|
66
|
+ */
|
|
67
|
+ private static double getAccuracy(long size) {
|
|
68
|
+ double accuracy;
|
|
69
|
+ if (size < 900) {
|
|
70
|
+ accuracy = 0.85;
|
|
71
|
+ } else if (size < 2047) {
|
|
72
|
+ accuracy = 0.6;
|
|
73
|
+ } else if (size < 3275) {
|
|
74
|
+ accuracy = 0.44;
|
|
75
|
+ } else {
|
|
76
|
+ accuracy = 0.4;
|
|
77
|
+ }
|
|
78
|
+ return accuracy;
|
|
79
|
+ }
|
|
80
|
+
|
|
81
|
+}
|