方案一:(压缩效果不理想)

  1. package com.soyuan.bigdata;
  2. import com.sun.image.codec.jpeg.JPEGCodec;
  3. import com.sun.image.codec.jpeg.JPEGEncodeParam;
  4. import com.sun.image.codec.jpeg.JPEGImageEncoder;
  5. import javax.imageio.ImageIO;
  6. import java.awt.*;
  7. import java.awt.image.BufferedImage;
  8. import java.io.*;
  9. public class PicReduce {
  10. /**
  11. * 直接指定压缩后的宽高:
  12. * (先保存原文件,再压缩、上传)
  13. * 壹拍项目中用于二维码压缩
  14. * @param oldFile 要进行压缩的文件全路径
  15. * @param width 压缩后的宽度
  16. * @param height 压缩后的高度
  17. * @param quality 压缩质量
  18. * @param smallIcon 文件名的小小后缀(注意,非文件后缀名称),入压缩文件名是yasuo.jpg,则压缩后文件名是yasuo(+smallIcon).jpg
  19. * @return 返回压缩后的文件的全路径
  20. */
  21. public static String zipImageFile(String oldFile, int width, int height,
  22. float quality, String smallIcon) {
  23. if (oldFile == null) {
  24. return null;
  25. }
  26. String newImage = null;
  27. try {
  28. /**对服务器上的临时文件进行处理 */
  29. Image srcFile = ImageIO.read(new File(oldFile));
  30. /** 宽,高设定 */
  31. BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  32. tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null);
  33. String filePrex = oldFile.substring(0, oldFile.indexOf('.'));
  34. /** 压缩后的文件名 */
  35. newImage = filePrex + smallIcon + oldFile.substring(filePrex.length());
  36. /** 压缩之后临时存放位置 */
  37. FileOutputStream out = new FileOutputStream(newImage);
  38. JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  39. JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
  40. /** 压缩质量 */
  41. jep.setQuality(quality, true);
  42. encoder.encode(tag, jep);
  43. out.close();
  44. } catch (FileNotFoundException e) {
  45. e.printStackTrace();
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. return newImage;
  50. }
  51. /**
  52. * 保存文件到服务器临时路径(用于文件上传)
  53. * @param fileName
  54. * @param is
  55. * @return 文件全路径
  56. */
  57. public static String writeFile(String fileName, InputStream is) {
  58. if (fileName == null || fileName.trim().length() == 0) {
  59. return null;
  60. }
  61. try {
  62. /** 首先保存到临时文件 */
  63. FileOutputStream fos = new FileOutputStream(fileName);
  64. byte[] readBytes = new byte[512];// 缓冲大小
  65. int readed = 0;
  66. while ((readed = is.read(readBytes)) > 0) {
  67. fos.write(readBytes, 0, readed);
  68. }
  69. fos.close();
  70. is.close();
  71. } catch (FileNotFoundException e) {
  72. e.printStackTrace();
  73. } catch (IOException e) {
  74. e.printStackTrace();
  75. }
  76. return fileName;
  77. }
  78. /**
  79. * 等比例压缩算法:
  80. * 算法思想:根据压缩基数和压缩比来压缩原图,生产一张图片效果最接近原图的缩略图
  81. * @param srcURL 原图地址
  82. * @param deskURL 缩略图地址
  83. * @param comBase 压缩基数
  84. * @param scale 压缩限制(宽/高)比例 一般用1:
  85. * 当scale>=1,缩略图height=comBase,width按原图宽高比例;若scale<1,缩略图width=comBase,height按原图宽高比例
  86. * @throws Exception
  87. * @author shenbin
  88. * @createTime 2014-12-16
  89. * @lastModifyTime 2014-12-16
  90. */
  91. public static void saveMinPhoto(String srcURL, String deskURL, double comBase,
  92. double scale) throws Exception {
  93. File srcFile = new File(srcURL);
  94. Image src = ImageIO.read(srcFile);
  95. int srcHeight = src.getHeight(null);
  96. int srcWidth = src.getWidth(null);
  97. int deskHeight = 0;// 缩略图高
  98. int deskWidth = 0;// 缩略图宽
  99. double srcScale = (double) srcHeight / srcWidth;
  100. /**缩略图宽高算法*/
  101. if ((double) srcHeight > comBase || (double) srcWidth > comBase) {
  102. if (srcScale >= scale || 1 / srcScale > scale) {
  103. if (srcScale >= scale) {
  104. deskHeight = (int) comBase;
  105. deskWidth = srcWidth * deskHeight / srcHeight;
  106. } else {
  107. deskWidth = (int) comBase;
  108. deskHeight = srcHeight * deskWidth / srcWidth;
  109. }
  110. } else {
  111. if ((double) srcHeight > comBase) {
  112. deskHeight = (int) comBase;
  113. deskWidth = srcWidth * deskHeight / srcHeight;
  114. } else {
  115. deskWidth = (int) comBase;
  116. deskHeight = srcHeight * deskWidth / srcWidth;
  117. }
  118. }
  119. } else {
  120. deskHeight = srcHeight;
  121. deskWidth = srcWidth;
  122. }
  123. BufferedImage tag = new BufferedImage(deskWidth, deskHeight, BufferedImage.TYPE_3BYTE_BGR);
  124. tag.getGraphics().drawImage(src, 0, 0, deskWidth, deskHeight, null); //绘制缩小后的图
  125. FileOutputStream deskImage = new FileOutputStream(deskURL); //输出到文件流
  126. JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(deskImage);
  127. encoder.encode(tag); //近JPEG编码
  128. deskImage.close();
  129. }
  130. public static void main(String args[]) throws Exception {
  131. // zipImageFile("/Users/tony/Desktop/index.jpg ", 1280, 1280, 1f, "x2");
  132. String baseDir = "/Users/twx/code-space/company/bigdata/dashboard-heartbeat/heart-beat-core/src/main/resources/static/img/";
  133. String outDir = "/Users/twx/code-space/company/bigdata/dashboard-heartbeat/heart-beat-core/src/main/resources/static/compress/";
  134. File dir = new File(baseDir);
  135. File[] files = dir.listFiles();
  136. for (File file : files) {
  137. String name = file.getName();
  138. System.out.println(file.getPath());
  139. String suffix = name.substring(name.indexOf(".") + 1);
  140. if (suffix.equals("png")) {
  141. saveMinPhoto(file.getPath(),outDir+name,2000,1);
  142. }
  143. }
  144. /*saveMinPhoto("/Users/twx/code-space/company/bigdata/dashboard-heartbeat/heart-beat-core/src/main/resources/static/img/out_dalian.png",
  145. "/Users/twx/code-space/company/bigdata/dashboard-heartbeat/heart-beat-core/src/main/resources/static/img/out_dalian_1.png",
  146. 2000, 1);*/
  147. }
  148. }

方案二:(推荐)

github地址:https://github.com/coobird/thumbnailator

pom

<dependency>
  <groupId>net.coobird</groupId>
  <artifactId>thumbnailator</artifactId>
  <version>0.4.8</version>
</dependency>

java

//压缩
Thumbnails.of(filePath)
    .scale(1f)
    .outputQuality(0.5f)
    .toFile(filePath);