xiongzhu 4 éve
szülő
commit
e5101cc07e

+ 34 - 1
src/main/java/com/izouma/nineth/utils/ImageUtils.java

@@ -1,8 +1,41 @@
 package com.izouma.nineth.utils;
 
+import net.coobird.thumbnailator.Thumbnails;
+import org.pngquant.PngQuant;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
 public class ImageUtils {
 
-    public static void compressJpg() {
+    public static BufferedImage resizeJpg(InputStream image, int width, int height) throws IOException {
+        BufferedImage bufferedImage = ImageIO.read(image);
+        return Thumbnails.of(bufferedImage)
+                .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
+                .outputFormat("jpg")
+                .asBufferedImage();
+    }
+
+    public static BufferedImage resizePng(InputStream image, int width, int height, boolean compress) throws IOException {
+        BufferedImage bufferedImage = ImageIO.read(image);
+        BufferedImage img = Thumbnails.of(bufferedImage)
+                .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
+                .outputFormat("png")
+                .asBufferedImage();
+        bufferedImage.flush();
+        PngQuant pngQuant = new PngQuant();
+        return pngQuant.getRemapped(img);
+    }
 
+    public static void main(String[] args) throws IOException {
+        ImageUtils.resizePng(new FileInputStream("/Users/drew/Downloads/盲盒详情.png"), 1000, 2000,true);
+        PngQuant pngQuant = new PngQuant();
+        ImageIO.write(pngQuant
+                        .getRemapped(ImageIO.read(new File("/Users/drew/Desktop/1.png"))),
+                "png", new File("/Users/drew/Desktop/2.png"));
     }
 }

+ 41 - 34
src/main/java/com/izouma/nineth/web/FileUploadController.java

@@ -3,6 +3,7 @@ package com.izouma.nineth.web;
 import com.izouma.nineth.domain.FileObject;
 import com.izouma.nineth.exception.BusinessException;
 import com.izouma.nineth.service.storage.StorageService;
+import com.izouma.nineth.utils.ImageUtils;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.FilenameUtils;
@@ -47,47 +48,53 @@ public class FileUploadController {
                              @RequestParam(value = "width", required = false) Integer width,
                              @RequestParam(value = "height", required = false) Integer height) throws IOException {
 
-        if (width != null && height == null) {
-            height = Integer.MAX_VALUE;
-        }
-        if (height != null && width == null) {
-            width = Integer.MAX_VALUE;
-        }
-
         String ext = Optional.ofNullable(FilenameUtils.getExtension(file.getOriginalFilename())).orElse("")
                 .toLowerCase().replace("jpeg", "jpg");
-        if (Pattern.matches("(jpg|png)", ext)) {
-            File tmpFile = null;
-            try {
-                tmpFile = File.createTempFile("upload", "." + ext);
-                FileUtils.copyToFile(file.getInputStream(), tmpFile);
-            } catch (IOException e) {
-                e.printStackTrace();
-                throw new BusinessException("上传失败");
-            }
-            PngQuant pngQuant = new PngQuant();
-            ImageIO.write(pngQuant.getRemapped(ImageIO.read(file.getInputStream())),
-                    "png", new File("/Users/drew/Downloads/111.png"));
-        }
-
         if (path == null) {
-            String basePath = "application";
-            try {
-                basePath = file.getContentType().split("/")[0];
-            } catch (Exception ignored) {
-            }
+            String basePath = Optional.ofNullable(file.getContentType()).orElse("application").split("/")[0];
             path = basePath + "/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
                     + RandomStringUtils.randomAlphabetic(8)
-                    + "." + FilenameUtils.getExtension(file.getOriginalFilename());
+                    + "." + ext;
         }
-        InputStream is;
-        try {
-            is = file.getInputStream();
-        } catch (IOException e) {
-            log.error("上传失败", e);
-            throw new BusinessException("上传失败", e.getMessage());
+
+        if (Pattern.matches("(jpg|png)", ext) && compress) {
+            if (width == null && height == null) {
+                width = Integer.MAX_VALUE;
+                height = Integer.MAX_VALUE;
+            } else if (height == null) {
+                height = Integer.MAX_VALUE;
+            } else if (width == null) {
+                width = Integer.MAX_VALUE;
+            }
+            BufferedImage img = null;
+            if ("jpg".equals(ext)) {
+                img = ImageUtils.resizeJpg(file.getInputStream(), width, height);
+            } else if ("png".equals(ext)) {
+                img = ImageUtils.resizePng(file.getInputStream(), width, height, true);
+            }
+            ByteArrayOutputStream os = new ByteArrayOutputStream();
+            ImageIO.write(img, ext, os);
+            InputStream is = new ByteArrayInputStream(os.toByteArray());
+            return storageService.uploadFromInputStream(is, path);
+        } else if (width != null || height != null) {
+            if (height == null) {
+                height = Integer.MAX_VALUE;
+            } else if (width == null) {
+                width = Integer.MAX_VALUE;
+            }
+            BufferedImage img = null;
+            if ("jpg".equals(ext)) {
+                img = ImageUtils.resizeJpg(file.getInputStream(), width, height);
+            } else if ("png".equals(ext)) {
+                img = ImageUtils.resizePng(file.getInputStream(), width, height, false);
+            }
+            ByteArrayOutputStream os = new ByteArrayOutputStream();
+            ImageIO.write(img, ext, os);
+            InputStream is = new ByteArrayInputStream(os.toByteArray());
+            return storageService.uploadFromInputStream(is, path);
         }
-        return storageService.uploadFromInputStream(is, path);
+
+        return storageService.uploadFromInputStream(file.getInputStream(), path);
     }
 
     @PostMapping("/base64")

+ 2 - 3
src/main/resources/application.yaml

@@ -33,9 +33,9 @@ spring:
         enable_lazy_load_no_trans: true
     open-in-view: true
   redis:
-    host: 118.178.226.110
+    host: 120.78.235.238
     port: 6379
-    password: 3edc#EDC
+    password: 98dwT6ghgoRVxwcRrDDy
     lettuce:
       pool:
         max_active: 8
@@ -133,7 +133,6 @@ spring:
     url: jdbc:mysql://rm-wz9y2p75f51a2o19k.mysql.rds.aliyuncs.com:53306/9th_test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2b8
   redis:
     host: 127.0.0.1
-    password:
 general:
   host: https://nft.9space.vip
 wx:

+ 2 - 1
src/test/java/com/izouma/nineth/CommonTest.java

@@ -194,7 +194,7 @@ public class CommonTest {
     @Test
     public void thumbnailator() throws IOException, ImageProcessException {
         Thumbnails.of(new File("/Users/drew/Downloads/2021-11-01-17-47-55zMwbSlgJ.jpeg"))
-                .size(1000, 1000)
+                .size(3000, 3000)
                 .outputFormat("jpg")
                 .toFile("/Users/drew/Desktop/1.jpg");
 
@@ -311,4 +311,5 @@ public class CommonTest {
             System.out.println(winItem.getName() + (winItem.isRare() ? "\t+++" : ""));
         }
     }
+
 }