Explorar el Código

增加图片上传压缩

wanxl hace 1 año
padre
commit
90b98e67d4

+ 6 - 0
pom.xml

@@ -440,6 +440,12 @@
             <artifactId>minio</artifactId>
             <version>8.5.9</version>
         </dependency>
+        <!--图片压缩webp-->
+        <dependency>
+            <groupId>org.sejda.imageio</groupId>
+            <artifactId>webp-imageio</artifactId>
+            <version>0.1.6</version>
+        </dependency>
     </dependencies>
 
     <dependencyManagement>

+ 85 - 9
src/main/java/com/sqx/modules/file/AliFileUploadController.java

@@ -3,6 +3,7 @@ package com.sqx.modules.file;
 import cn.hutool.core.util.StrUtil;
 import com.aliyun.oss.OSS;
 import com.aliyun.oss.OSSClientBuilder;
+import com.luciad.imageio.webp.WebPWriteParam;
 import com.sqx.common.exception.SqxException;
 import com.sqx.common.utils.Result;
 import com.sqx.config.MinioConfig;
@@ -16,21 +17,32 @@ import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.fileupload.disk.DiskFileItem;
+import org.apache.commons.lang.StringUtils;
+import org.apache.poi.util.IOUtils;
 import org.jaudiotagger.audio.AudioFileIO;
 import org.jaudiotagger.audio.mp3.MP3AudioHeader;
 import org.jaudiotagger.audio.mp3.MP3File;
+import org.springframework.boot.system.ApplicationHome;
+import org.springframework.util.ClassUtils;
+import org.springframework.util.StreamUtils;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.multipart.commons.CommonsMultipartFile;
 
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
+import javax.imageio.IIOImage;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.ImageWriter;
+import javax.imageio.stream.FileImageOutputStream;
+import javax.imageio.stream.ImageOutputStream;
+import java.awt.image.BufferedImage;
+import java.io.*;
+import java.net.URLDecoder;
+import java.nio.file.Files;
 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.HashMap;
@@ -81,11 +93,60 @@ public class AliFileUploadController {
             // Minio上传
             String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
             String completePath = getPath(suffix);
+            long fileSize =file.getSize();
             try {
+                InputStream inputStream=file.getInputStream();
+                if(this.isPicture(suffix)&&file.getSize()>1024*1024*2){
+                    completePath=getPath(".webp");
+                    String tmpPath =UUID.randomUUID().toString().replaceAll("-", "")+".webp";
+                    ApplicationHome applicationHome = new ApplicationHome(AliFileUploadController.class);
+                    String pathResouce = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath();
+                    String decode = URLDecoder.decode(pathResouce, "utf-8");
+                    File newFile = new File(decode + tmpPath);
+                    ImageOutputStream  ios=null;
+                    try {
+                        BufferedImage image = ImageIO.read(inputStream);
+                        ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
+                        WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
+                        writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
+                        // 设置有损压缩
+                        writeParam.setCompressionType(writeParam.getCompressionTypes()[WebPWriteParam.LOSSY_COMPRESSION]);
+                        //设置 80% 的质量. 设置范围 0-1
+                        writeParam.setCompressionQuality(0.8f);
+                        // Save the image
+                        ios =ImageIO.createImageOutputStream(newFile);
+                        writer.setOutput(ios);
+                        writer.write(null, new IIOImage(image, null, null), writeParam);
+                        writer.dispose();
+                        ios.close();
+                        minioClient.putObject(PutObjectArgs.builder()
+                                .bucket(minioConfig.getBucket())
+                                .object(completePath)
+                                .stream(Files.newInputStream(newFile.toPath()), newFile.length(), -1)
+                                .build());
+                        inputStream.close();
+                        delteTempFile(newFile);
+                        String src = commonRepository.findOne(72).getValue() + "/" + completePath;
+                        return Result.success().put("data", src);
+                    } catch (IOException e) {
+                        throw new RuntimeException(e);
+                    }finally {
+                        try {
+                            if(inputStream!=null){
+                                inputStream.close();
+                            }
+                            if(ios!=null){
+                                ios.close();
+                            }
+                        } catch (IOException e) {
+                            log.info(e.getMessage());
+                        }
+                    }
+                }
                 minioClient.putObject(PutObjectArgs.builder()
                         .bucket(minioConfig.getBucket())
                         .object(completePath)
-                        .stream(file.getInputStream(), file.getSize(), -1)
+                        .stream(inputStream, fileSize, -1)
                         .build());
 
                 String src = commonRepository.findOne(72).getValue() + "/" + completePath;
@@ -93,7 +154,6 @@ public class AliFileUploadController {
             } catch (Exception e) {
                 throw new SqxException("文件上传失败!");
             }
-
         } else{
             try
             {
@@ -286,7 +346,23 @@ public class AliFileUploadController {
         }
         return null;
     }
-
+    /**
+     * 判断文件是否为图片
+     */
+    public boolean isPicture(String imgName) {
+        boolean flag = false;
+        if (StringUtils.isBlank(imgName)) {
+            return false;
+        }
+        String[] arr = {".bmp", ".dib", ".gif", ".jfif", ".jpe", ".jpeg", ".jpg", ".png", ".tif", ".tiff", ".ico"};
+        for (String item : arr) {
+            if (item.equals(imgName)) {
+                flag = true;
+                break;
+            }
+        }
+        return flag;
+    }
 
 
 }

+ 1 - 1
src/main/resources/application-dev.yml

@@ -47,7 +47,7 @@ spring:
                 max-wait: -1
 secure-api:
     # 开启SecureApi功能,如果为false则其余配置项均不生效
-    enabled: true
+    enabled: false
     # 开启加解密日志打印,会打印出接口名、加密模式、算法、明文和密文等信息
     show-log: true
     url-safe: true