Przeglądaj źródła

图片上传压缩缩略接口和原图片替换处理任务方法

cup 3 lat temu
rodzic
commit
c47bc6a8d5

+ 98 - 7
mp-admin/src/main/java/com/qs/mp/web/controller/common/FileUploadController.java

@@ -1,7 +1,9 @@
 package com.qs.mp.web.controller.common;
 
 
+import com.alibaba.druid.sql.visitor.functions.If;
 import com.qs.mp.common.core.domain.AjaxResult;
+import com.qs.mp.common.enums.PicHandlerTypeEnum;
 import com.qs.mp.common.qcloud.QcloudFileUtils;
 import com.qs.mp.common.utils.LogUtil;
 import com.qs.mp.common.utils.StringUtils;
@@ -99,12 +101,25 @@ public class FileUploadController extends BaseApiController {
      */
     @PostMapping("image/remote/upload/post/{auth}")
     public AjaxResult postImage(@PathVariable("auth") int auth, @RequestParam("file") MultipartFile file)  {
-        return uploadImageFile(auth, file);
+        return uploadImageFile(auth, file, PicHandlerTypeEnum.CROP.getValue());
     }
 
+    @PostMapping("image/remote/upload/post/commpress/{type}")
+    public AjaxResult postCommpressImage(@PathVariable("type") int type, @RequestParam("file") MultipartFile file)  {
+        return uploadImageFile(0, file, type);
+    }
+
+    /**
+     * 上传图形方法
+     * @param auth  认证
+     * @param file  文件信息
+     * @param handlerType   处理类型,1 裁剪,2 压缩
+     * @return
+     */
     private AjaxResult uploadImageFile(
         @PathVariable("auth") int auth,
-        @RequestParam("file") MultipartFile file) {
+        @RequestParam("file") MultipartFile file,
+        int handlerType) {
         try {
             if (null == file) {
                 return AjaxResult.error("上传文件参数为空.");
@@ -122,7 +137,14 @@ public class FileUploadController extends BaseApiController {
                 mimeType = "image/jpg";
             }
             LogUtil.info(logger," mimeType:" + mimeType + " fileName:" + file.getOriginalFilename());
-            String name = commpressPicAndUpLoadOSS(file, mimeType, 480, 480, bucketName);
+            String name = "";
+            if (PicHandlerTypeEnum.CROP.getValue().equals(handlerType)) {
+                // 裁剪并上传图片
+                name = cropPicAndUpLoadOSS(file, mimeType, 480, 480, bucketName);
+            }else if (PicHandlerTypeEnum.COMPRESSION.getValue().equals(handlerType)) {
+                // 压缩并上传图片
+                name = commpressPicAndUpLoadOSS(file, mimeType, bucketName);
+            }
             if (StringUtils.isBlank(name)) {
                 LogUtil.error(logger, "图片上传失败.");
                 return AjaxResult.error("图片上传失败.");
@@ -143,12 +165,19 @@ public class FileUploadController extends BaseApiController {
      */
     @PutMapping("image/remote/upload/{auth}")
     public AjaxResult uploadImage(@PathVariable("auth") int auth, @RequestParam("file") MultipartFile file)  {
-        return uploadImageFile(auth, file);
+        return uploadImageFile(auth, file, PicHandlerTypeEnum.CROP.getValue());
     }
 
-
-
-    private String commpressPicAndUpLoadOSS(MultipartFile file,String mimeType,int width,int height,String bucketName) {
+    /**
+     * 裁剪图片并上传
+     * @param file
+     * @param mimeType
+     * @param width
+     * @param height
+     * @param bucketName
+     * @return
+     */
+    private String cropPicAndUpLoadOSS(MultipartFile file,String mimeType,int width,int height,String bucketName) {
         String fileName = file.getOriginalFilename();
         int idx = fileName.lastIndexOf('.');
         String suffix = "";
@@ -191,4 +220,66 @@ public class FileUploadController extends BaseApiController {
         }
         return name;
     }
+
+
+    /**
+     * 压缩并上传图片
+     * @param file
+     * @param mimeType
+     * @param bucketName
+     * @return
+     */
+    private String commpressPicAndUpLoadOSS(MultipartFile file, String mimeType, String bucketName){
+        String fileName = file.getOriginalFilename();
+        int idx = fileName.lastIndexOf('.');
+        String suffix = "";
+        if (idx > 0) {
+            suffix = fileName.substring(idx);
+        }
+        String name = UUIDUtils.newId() + suffix;
+        try {
+            QcloudFileUtils.putStream(file.getInputStream(), name, bucketName, mimeType );
+            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
+            Builder<BufferedImage> builder = Thumbnails.of(bufferedImage);
+
+
+            int pWidth = bufferedImage.getWidth();
+            int pHeight = bufferedImage.getHeight();
+            builder.size(pWidth, pHeight);
+
+            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);
+
+            // 压缩图片
+            Thumbnails.of(outFilePath).scale(0.5f).outputQuality(0.5f).toFile(outFilePath);
+
+            // 压缩图片
+            if (pWidth > 500) {
+
+                float scale = 500f / pWidth;
+
+                Thumbnails.of(outFilePath).scale(scale).outputQuality(0.5f).toFile(outFilePath);
+            }else {
+                Thumbnails.of(outFilePath).scale(1f).outputQuality(0.5f).toFile(outFilePath);
+            }
+
+
+            File outFile = new File(outFilePath);
+            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;
+        }
+        return name;
+    }
 }

+ 31 - 0
mp-common/src/main/java/com/qs/mp/common/enums/PicHandlerTypeEnum.java

@@ -0,0 +1,31 @@
+package com.qs.mp.common.enums;
+
+import com.baomidou.mybatisplus.annotation.IEnum;
+import io.swagger.annotations.ApiModel;
+
+/**
+ * 图片处理类型枚举
+ * @author Cup
+ * @date 2022/4/15
+ */
+@ApiModel(value = "图片处理类型枚举")
+public enum PicHandlerTypeEnum implements IEnum<Integer> {
+
+    CROP(1, "裁剪"),
+    COMPRESSION(2, "压缩");
+
+
+    private final int value;
+    private final String desc;
+
+    PicHandlerTypeEnum(int value, String desc) {
+        this.value = value;
+        this.desc = desc;
+    }
+
+    @Override
+    public Integer getValue() {
+        return value;
+    }
+
+}

+ 163 - 0
mp-quartz/src/main/java/com/qs/mp/quartz/task/CosTask.java

@@ -0,0 +1,163 @@
+package com.qs.mp.quartz.task;
+
+import cn.hutool.core.img.Img;
+import com.qcloud.cos.COSClient;
+import com.qcloud.cos.exception.CosClientException;
+import com.qcloud.cos.exception.CosServiceException;
+import com.qcloud.cos.model.*;
+import com.qs.mp.common.core.domain.AjaxResult;
+import com.qs.mp.common.enums.PicHandlerTypeEnum;
+import com.qs.mp.common.qcloud.QcloudFileUtils;
+import com.qs.mp.common.utils.LogUtil;
+import com.qs.mp.common.utils.StringUtils;
+import com.qs.mp.common.utils.UUIDUtils;
+import com.qs.mp.core.domain.LoginUser;
+import com.qs.mp.core.domain.UploadAttachment;
+import net.coobird.thumbnailator.Thumbnails;
+import net.coobird.thumbnailator.geometry.Positions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.*;
+import java.util.ArrayList;
+import java.util.List;
+
+
+/**
+ * 腾讯 COS 操作任务
+ *
+ * @author Cup
+ * @date 2022/4/15
+ */
+@Component("CosTask")
+public class CosTask {
+
+    protected final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());
+
+
+    /**
+     * 文件上传路径
+     */
+    @Value("${mp.profile}")
+    public String filePath;
+
+    /**
+     * 公开
+     */
+    @Value("${cloud.public-bucket-name}")
+    private String publicBucketName;
+
+
+    /**
+     * 腾讯COS图片压缩替换任务
+     */
+    public void compressPicture() throws IOException, InterruptedException {
+        LogUtil.info(logger, "...图片压缩替换任务开始...");
+
+        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
+        // 设置bucket名称
+        listObjectsRequest.setBucketName(publicBucketName);
+        // prefix表示列出的object的key以prefix开始
+        listObjectsRequest.setPrefix("/");
+        // deliter表示分隔符, 设置为/表示列出当前目录下的object, 设置为空表示列出所有的object
+        listObjectsRequest.setDelimiter("/");
+        // 设置最大遍历出多少个对象, 一次listobject最大支持1000
+        listObjectsRequest.setMaxKeys(500);
+        ObjectListing objectListing = null;
+        do {
+            try {
+                COSClient cosClient = QcloudFileUtils.getCosClient();
+                objectListing = cosClient.listObjects(listObjectsRequest);
+            } catch (CosServiceException e) {
+                e.printStackTrace();
+                return;
+            } catch (CosClientException e) {
+                e.printStackTrace();
+                return;
+            }
+            // common prefix表示表示被delimiter截断的路径, 如delimter设置为/, common prefix则表示所有子目录的路径
+            List<String> commonPrefixs = objectListing.getCommonPrefixes();
+
+            // object summary表示所有列出的object列表
+            List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
+
+            for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
+                // 文件的路径key
+                String key = cosObjectSummary.getKey();
+
+                if (key.length() < 6) {
+                    continue;
+                }
+
+                if (".jpg_s".equals(key.substring(key.length() - 6))) {
+
+                    // 获取原图文件名
+                    String picName = key.substring(0, key.length() - 2);
+                    System.err.println("key = " + picName);
+                    uploadAndCommpressImg(picName);
+
+                }
+            }
+            String nextMarker = objectListing.getNextMarker();
+            listObjectsRequest.setMarker(nextMarker);
+        } while (objectListing.isTruncated());
+
+        LogUtil.info(logger, "...图片压缩替换完成!!...");
+    }
+
+    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 downObjectMeta = cosClient.getObject(getObjectRequest, downFile);
+        FileInputStream fileInputStream = new FileInputStream(path);
+        String mimeType = "image/jpg";
+        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);
+
+        String outFileDir = filePath + "/thumb";
+        File tempFile = new File(outFileDir);
+        if (!tempFile.exists()) {
+            tempFile.mkdirs();
+        }
+        String thumbName = key + "_s";
+        String outFilePath = filePath + "/thumb/" + thumbName + "." + mimeType.substring(mimeType.lastIndexOf("/") + 1);
+        builder.toFile(outFilePath);
+
+        // 压缩图片
+        if (pWidth > 500) {
+
+            float scale = 500f / pWidth;
+
+            Thumbnails.of(outFilePath).scale(scale).outputQuality(0.5f).toFile(outFilePath);
+        }else {
+            Thumbnails.of(outFilePath).scale(1f).outputQuality(0.5f).toFile(outFilePath);
+        }
+
+
+        File outFile = new File(outFilePath);
+        QcloudFileUtils.putFile(outFile, thumbName, publicBucketName, mimeType);
+
+        downFile.delete();
+        outFile.delete();
+
+
+    }
+
+
+}