Browse Source

优化生成缩略图

chunping 3 years ago
parent
commit
bd5473633e

+ 22 - 36
mp-admin/src/main/java/com/qs/mp/web/controller/common/FileUploadController.java

@@ -4,6 +4,7 @@ package com.qs.mp.web.controller.common;
 import com.qs.mp.common.core.domain.AjaxResult;
 import com.qs.mp.common.enums.PicHandlerTypeEnum;
 import com.qs.mp.common.image.CompressUtil;
+import com.qs.mp.common.image.ThumbnailsImgFilter;
 import com.qs.mp.common.qcloud.QcloudFileUtils;
 import com.qs.mp.common.utils.LogUtil;
 import com.qs.mp.common.utils.StringUtils;
@@ -239,8 +240,6 @@ public class FileUploadController extends BaseApiController {
             suffix = fileName.substring(idx);
         }
         String name = UUIDUtils.newId() + suffix;
-        ByteArrayInputStream inputStream = null;
-        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
         try {
             QcloudFileUtils.putStream(file.getInputStream(), name, bucketName, mimeType );
             BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
@@ -249,63 +248,50 @@ public class FileUploadController extends BaseApiController {
 
             int pWidth = bufferedImage.getWidth();
             int pHeight = bufferedImage.getHeight();
+            builder.size(pWidth, pHeight);
             double accuracy = CompressUtil.getAccuracy(file.getSize()/1024);
-            LogUtil.info(logger, "原始文件宽:{0},大小:{1},压缩比:{2}", pWidth, file.getSize()/1024, accuracy);
-//            builder.size(pWidth, pHeight);
+            LogUtil.info(logger, "原始文件长:{0},大小:{1},压缩比:{2}", pWidth, file.getSize()/1024, accuracy);
 
-            /*String outFileDir = filePath+"/thumb";
+            String outFileDir = filePath+"/thumb";
             File tempFile = new File(outFileDir);
             if(!tempFile.exists()) {
                 tempFile.mkdirs();
-            }*/
+            }
             String thumbName = name +"_s";
-//            String outFilePath = filePath+"/thumb/"+thumbName+"."+mimeType.substring(mimeType.lastIndexOf("/")+1);
-//            builder.toFile(outFilePath);
+            String outFilePath = filePath+"/thumb/"+thumbName+"."+mimeType.substring(mimeType.lastIndexOf("/")+1);
+            builder.toFile(outFilePath);
 
             // 压缩图片
-            if (pWidth > 500) {
-                float scale = 500f / pWidth;
+            if (pWidth > 750) {
+                float scale = 750f / pWidth;
                 if ("image/png".equals(file.getContentType())) {
-                    Thumbnails.of(file.getInputStream()).scale(scale).outputQuality(accuracy)
+                    Thumbnails.of(outFilePath).scale(scale).outputQuality(accuracy)
                         .imageType(BufferedImage.TYPE_INT_ARGB).outputFormat("png")
-                        .toOutputStream(outputStream);
+                        .toFile(outFilePath);
                 } else {
-                    Thumbnails.of(file.getInputStream()).scale(scale).outputQuality(accuracy)
-                        .toOutputStream(outputStream);
+                    Thumbnails.of(outFilePath).scale(scale).outputQuality(accuracy).toFile(outFilePath);
                 }
             }else {
                 if ("image/png".equals(file.getContentType())) {
-                    Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(accuracy)
+                    Thumbnails.of(outFilePath).scale(1f).outputQuality(accuracy)
                         .imageType(BufferedImage.TYPE_INT_ARGB).outputFormat("png")
-                        .toOutputStream(outputStream);
+                        .toFile(outFilePath);
                 } else {
-                    Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(accuracy)
-                        .toOutputStream(outputStream);
+                    Thumbnails.of(outFilePath).scale(1f).outputQuality(accuracy).toFile(outFilePath);
                 }
             }
-            LogUtil.info(logger, "压缩后文件大小:{0}", outputStream.toByteArray().length / 1024);
 
-            inputStream = new ByteArrayInputStream(outputStream.toByteArray());
-            QcloudFileUtils.putStream(inputStream, thumbName, bucketName, mimeType);
 
+            File outFile = new File(outFilePath);
+            LogUtil.info(logger, "压缩后文件大小:{0}", outFile.length()/ 1024);
+            QcloudFileUtils.putFile(outFile, thumbName, bucketName, mimeType);
+            if(outFile.exists()) {
+                LogUtil.info(log, "delete file..."+outFilePath);
+                outFile.delete();
+            }
         }  catch (Exception e) {
             LogUtil.error(log, e, "");
             return null;
-        } finally{
-            if (inputStream != null){
-                try{
-                    inputStream.close();
-                }catch (IOException e){
-                    LogUtil.error(log, e, "关闭输入流失败");
-                }
-            }
-            if (outputStream != null){
-                try{
-                    outputStream.close();
-                }catch (IOException e){
-                    LogUtil.error(log, e, "关闭输出流失败");
-                }
-            }
         }
         return name;
     }

+ 3 - 3
mp-common/src/main/java/com/qs/mp/common/image/CompressUtil.java

@@ -19,9 +19,9 @@ public class CompressUtil {
 
   private static final Integer ZERO = 0;
   private static final Integer ONE_ZERO_TWO_FOUR = 1024;
-  private static final Integer NINE_ZERO_ZERO = 200;
-  private static final Integer THREE_TWO_SEVEN_FIVE = 1000;
-  private static final Integer TWO_ZERO_FOUR_SEVEN = 500;
+  private static final Integer NINE_ZERO_ZERO = 400;
+  private static final Integer THREE_TWO_SEVEN_FIVE = 2047;
+  private static final Integer TWO_ZERO_FOUR_SEVEN = 900;
   private static final Double ZERO_EIGHT_FIVE = 0.85;
   private static final Double ZERO_SIX = 0.6;
   private static final Double ZERO_FOUR_FOUR = 0.44;

+ 5 - 10
mp-common/src/main/java/com/qs/mp/common/jsms/JSMSUtils.java

@@ -66,11 +66,9 @@ public class JSMSUtils {
 
             }
         } catch (APIConnectionException e) {
-            logger.error("Connection error. Should retry later. ", e);
+            logger.error("Connection error. Should retry later. " + e.getMessage());
         } catch (APIRequestException e) {
-            logger.error("Error response from JPush server. Should review and fix it. ", e);
-            logger.info("HTTP Status: " + e.getStatus());
-            logger.info("Error Message: " + e.getMessage());
+            logger.error("Error response from JPush server. Should review and fix it. " + e.getMessage());
         }
         return null;
     }
@@ -95,9 +93,9 @@ public class JSMSUtils {
 
             }
         } catch (APIConnectionException e) {
-            LogUtil.error(logger, e, "短信发送失败,mobile:{0}", mobile);
+            LogUtil.error(logger, "短信发送失败,mobile:{0},msg:{1}", new Object[]{mobile, e.getMessage()});
         } catch (APIRequestException e) {
-            LogUtil.error(logger, e, "短信发送失败,mobile:{0}", mobile);
+            LogUtil.error(logger, "短信发送失败,mobile:{0},msg:{1}", new Object[]{mobile, e.getMessage()});
         }
         return null;
     }
@@ -140,12 +138,9 @@ public class JSMSUtils {
                 return (new GsonBuilder()).excludeFieldsWithoutExposeAnnotation().create().fromJson("{\"is_valid\":TRUE}", ValidSMSResult.class);
             }
         } catch (APIConnectionException e) {
-            logger.error("Connection error. Should retry later. ", e);
+            logger.error("Connection error. Should retry later. " +  e.getMessage());
         } catch (APIRequestException e) {
             logger.error(e.getStatus() + " errorCode: " + e.getErrorCode() + " " + e.getErrorMessage());
-            logger.error("Error response from JPush server. Should review and fix it. ", e);
-            logger.info("HTTP Status: " + e.getStatus());
-            logger.info("Error Message: " + e.getMessage());
         }
         return null;
     }

+ 48 - 50
mp-quartz/src/main/java/com/qs/mp/quartz/task/CosTask.java

@@ -3,23 +3,17 @@ package com.qs.mp.quartz.task;
 import com.qcloud.cos.COSClient;
 import com.qcloud.cos.exception.CosClientException;
 import com.qcloud.cos.exception.CosServiceException;
-import com.qcloud.cos.model.COSObject;
 import com.qcloud.cos.model.COSObjectSummary;
 import com.qcloud.cos.model.GetObjectRequest;
 import com.qcloud.cos.model.ListObjectsRequest;
 import com.qcloud.cos.model.ObjectListing;
 import com.qcloud.cos.model.ObjectMetadata;
+import com.qs.mp.common.image.CompressUtil;
 import com.qs.mp.common.qcloud.QcloudFileUtils;
 import com.qs.mp.common.utils.LogUtil;
-import io.lettuce.core.output.ByteArrayOutput;
 import java.awt.image.BufferedImage;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
 import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
 import java.io.IOException;
-import java.io.InputStream;
 import java.util.List;
 import javax.imageio.ImageIO;
 import net.coobird.thumbnailator.Thumbnails;
@@ -114,61 +108,65 @@ public class CosTask {
     LogUtil.info(logger, "...图片压缩替换完成!!...");
   }
 
-  private void uploadAndCommpressImg(String key) {
+  private void uploadAndCommpressImg(String key) throws IOException, InterruptedException {
     String path = filePath + "/thumb/" + key;
     File downFile = new File(path);
     GetObjectRequest getObjectRequest = new GetObjectRequest(publicBucketName, key);
     COSClient cosClient = QcloudFileUtils.getCosClient();
-    ObjectMetadata cosObjectmetadata = cosClient.getObject(getObjectRequest, downFile);
-    String mimeType = cosObjectmetadata.getContentType();
-    ByteArrayInputStream inputStream = null;
-    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+    ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, downFile);
+//        FileInputStream fileInputStream = new FileInputStream(path);
+    String contentType = downObjectMeta.getContentType();
+//        QcloudFileUtils.putStream(fileInputStream, key, publicBucketName, mimeType);
+
+    // 压缩图片
+    BufferedImage bufferedImage = ImageIO.read(downFile);
+    Thumbnails.Builder<BufferedImage> builder = Thumbnails.of(bufferedImage);
+    int pWidth = bufferedImage.getWidth();
+    int pHeight = bufferedImage.getHeight();
+    builder.size(pWidth, pHeight);
+    double accuracy = CompressUtil.getAccuracy(downObjectMeta.getContentLength()/1024);
+    LogUtil.info(logger, "原始文件长:{0},大小:{1},类型:{2},压缩比:{3}", pWidth, downObjectMeta.getContentLength()/1024, contentType, 0.8);
+
+    String outFileDir = filePath + "/thumb";
+    File tempFile = new File(outFileDir);
+    if (!tempFile.exists()) {
+      tempFile.mkdirs();
+    }
+    String thumbName = key + "_s";
+    String outFilePath =
+        filePath + "/thumb/" + thumbName + "." + contentType.substring(contentType.lastIndexOf("/") + 1);
+    builder.toFile(outFilePath);
+
+    // 压缩图片
     // 压缩图片
-    try {
-      BufferedImage bufferedImage = ImageIO.read(downFile);
-      Thumbnails.Builder<BufferedImage> builder = Thumbnails.of(bufferedImage);
-      int pWidth = bufferedImage.getWidth();
-      int pHeight = bufferedImage.getHeight();
-      String thumbName = key + "_s";
-
-      // 压缩图片
-      if (pWidth > 500) {
-        float scale = 500f / pWidth;
-        Thumbnails.of(downFile).scale(scale).outputQuality(0.8f).toOutputStream(outputStream);
+    if (pWidth > 750) {
+      float scale = 750f / pWidth;
+      if ("image/png".equals(contentType)) {
+        Thumbnails.of(outFilePath).scale(scale).outputQuality(0.8)
+            .imageType(BufferedImage.TYPE_INT_ARGB).outputFormat("png")
+            .toFile(outFilePath);
       } else {
-        Thumbnails.of(downFile).scale(1f).outputQuality(0.8f).toOutputStream(outputStream);
+        Thumbnails.of(outFilePath).scale(scale).outputQuality(0.8).toFile(outFilePath);
       }
-      inputStream = new ByteArrayInputStream(outputStream.toByteArray());
-      QcloudFileUtils.putStream(inputStream, thumbName, publicBucketName, mimeType);
-
-    } catch (Exception e) {
-      LogUtil.error(logger, e, "图片压缩上传异常");
-    } finally {
-      if (inputStream != null) {
-        try {
-          inputStream.close();
-        } catch (IOException e) {
-          LogUtil.error(logger, e, "关闭输入流失败");
-        }
-      }
-      if (outputStream != null) {
-        try {
-          outputStream.close();
-        } catch (IOException e) {
-          LogUtil.error(logger, e, "关闭输出流失败");
-        }
+    }else {
+      if ("image/png".equals(contentType)) {
+        Thumbnails.of(outFilePath).scale(1f).outputQuality(0.8)
+            .imageType(BufferedImage.TYPE_INT_ARGB).outputFormat("png")
+            .toFile(outFilePath);
+      } else {
+        Thumbnails.of(outFilePath).scale(1f).outputQuality(0.8).toFile(outFilePath);
       }
-//      if (cosObject != null) {
-//        try {
-//          cosObject.close();
-//        } catch (IOException e) {
-//          LogUtil.error(logger, e, "关闭cos对象失败");
-//        }
-//      }
     }
 
+    File outFile = new File(outFilePath);
+    QcloudFileUtils.putFile(outFile, thumbName, publicBucketName, contentType);
+    LogUtil.info(logger, "压缩后文件大小:{0}", outFile.length()/ 1024);
+    downFile.delete();
+    outFile.delete();
+
 
   }
 
 
 }
+