Просмотр исходного кода

优化图片文件处理流程

reghao 3 лет назад
Родитель
Сommit
869474371b

+ 13 - 48
src/main/java/cn/reghao/dfs/store/controller/ImageFileController.java

@@ -1,9 +1,7 @@
 package cn.reghao.dfs.store.controller;
 
 import cn.reghao.dfs.store.service.FileUrlService;
-import cn.reghao.dfs.store.service.media.MediaQuality;
-import cn.reghao.dfs.store.service.media.MediaResolution;
-import cn.reghao.dfs.store.util.media.ImageOps;
+import cn.reghao.dfs.store.service.media.ImageFileService;
 import org.springframework.core.io.InputStreamResource;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpStatus;
@@ -11,8 +9,6 @@ import org.springframework.http.MediaType;
 import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.*;
 
-import javax.imageio.ImageIO;
-import java.awt.image.BufferedImage;
 import java.io.*;
 
 /**
@@ -23,9 +19,11 @@ import java.io.*;
 @RequestMapping
 public class ImageFileController {
     private final FileUrlService fileUrlService;
+    private final ImageFileService imageFileService;
 
-    public ImageFileController(FileUrlService fileUrlService) {
+    public ImageFileController(FileUrlService fileUrlService, ImageFileService imageFileService) {
         this.fileUrlService = fileUrlService;
+        this.imageFileService = imageFileService;
     }
 
     @GetMapping("/image/{filename}")
@@ -49,60 +47,27 @@ public class ImageFileController {
     @GetMapping("/image1/{filename:.+}")
     public ResponseEntity<InputStreamResource> image1(@PathVariable("filename") String filename) throws Exception {
         String[] strs = filename.split("@");
-        /*String uploadId = strs[0].split("\\.")[0];
+        String uploadId = strs[0].split("\\.")[0];
         String filePath = fileUrlService.getFilePath(uploadId);
         if (filePath == null) {
             return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
-        }*/
+        }
 
+        InputStream inputStream;
         if (strs.length == 1) {
-            String filePath = "/home/reghao/Downloads/0.jpg";
-            InputStream inputStream = new FileInputStream(filePath);
-            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
-
-            HttpHeaders httpHeaders = new HttpHeaders();
-            httpHeaders.set("Pragma", "No-cache");
-            httpHeaders.set("Cache-Control", "no-cache");
-            return ResponseEntity.status(HttpStatus.OK).headers(httpHeaders).contentType(MediaType.IMAGE_JPEG)
-                    .body(inputStreamResource);
+            inputStream = new FileInputStream(filePath);
+        } else {
+            String[] params = strs[1].split("_");
+            int width = Integer.parseInt(params[0].replace("w", ""));
+            int height = Integer.parseInt(params[1].replace("h", ""));
+            inputStream = imageFileService.getImageStream(filePath, width, height);
         }
 
-        String[] params = strs[1].split("_");
-        int width = Integer.parseInt(params[0].replace("w", ""));
-        int height = Integer.parseInt(params[1].replace("h", ""));
-
-        String filePath = "/home/reghao/Downloads/0.jpg";
-        InputStream inputStream = getImageStream(filePath, width, height);
         InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
-
         HttpHeaders httpHeaders = new HttpHeaders();
         httpHeaders.set("Pragma", "No-cache");
         httpHeaders.set("Cache-Control", "no-cache");
         return ResponseEntity.status(HttpStatus.OK).headers(httpHeaders).contentType(MediaType.IMAGE_JPEG)
                 .body(inputStreamResource);
     }
-
-    private InputStream getImageStream(String filePath, int reqWidth, int reqHeight) throws IOException {
-        // TODO 添加一层缓存
-        File file = new File(filePath);
-        ImageOps.Size imgSize = ImageOps.info(file);
-        int width = imgSize.getWidth();
-        int height = imgSize.getHeight();
-
-        MediaResolution quality = MediaQuality.getQuality1(width, height);
-        int height1 = quality.getHeight();
-
-        MediaResolution reqQuality = MediaQuality.getQuality1(reqWidth, reqHeight);
-        int hight2 = reqQuality.getHeight();
-
-        if (height1 < hight2) {
-            return new FileInputStream(filePath);
-        } else {
-            int ratio = height1/hight2;
-            BufferedImage bufferedImage = ImageOps.resize(filePath, ratio);
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            ImageIO.write(bufferedImage, "jpg", baos);
-            return new ByteArrayInputStream(baos.toByteArray());
-        }
-    }
 }

+ 3 - 2
src/main/java/cn/reghao/dfs/store/controller/ImageUploadController.java

@@ -4,6 +4,7 @@ import cn.reghao.dfs.store.model.dto.*;
 import cn.reghao.dfs.store.model.vo.*;
 import cn.reghao.dfs.store.service.FileUploadService;
 import cn.reghao.dfs.store.service.media.ImageFileService;
+import cn.reghao.dfs.store.service.media.MediaResolution;
 import cn.reghao.jutil.jdk.result.WebBody;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
@@ -46,7 +47,7 @@ public class ImageUploadController {
 
         UploadingFile uploadingFile = new UploadingFile(file);
         UploadedFile uploadedFile = fileUploadService.put(uploadingFile);
-        ImageFileRet imageFileRet = imageFileService.process(uploadedFile);
+        ImageFileRet imageFileRet = imageFileService.process(uploadedFile, MediaResolution.p144);
 
         UploadFileRet uploadFileRet = new UploadFileRet(uploadedFile.getUploadId(), uploadedFile.getPathUrl().getUrl());
         return WebBody.success(uploadFileRet);
@@ -62,7 +63,7 @@ public class ImageUploadController {
 
         UploadingFile uploadingFile = new UploadingFile(file);
         UploadedFile uploadedFile = fileUploadService.put(uploadingFile);
-        ImageFileRet imageFileRet = imageFileService.process(uploadedFile);
+        ImageFileRet imageFileRet = imageFileService.process(uploadedFile, MediaResolution.p144);
         return WebBody.success(imageFileRet);
     }
 }

+ 3 - 3
src/main/java/cn/reghao/dfs/store/controller/VideoUploadController.java

@@ -43,8 +43,8 @@ public class VideoUploadController {
         }
 
         UploadingFile uploadingFile = new UploadingFile(file);
-        videoService.setVideoCover(videoFileId, uploadingFile);
-        return WebBody.success();
+        ImageFileRet imageFileRet = videoService.setVideoCover(videoFileId, uploadingFile);
+        return WebBody.success(imageFileRet);
     }
 
     @ApiOperation("文件上传前的准备, 客户端传递文件的 sha256sum, 文件若存在则直接返回文件关联的 id")
@@ -58,7 +58,7 @@ public class VideoUploadController {
     @GetMapping(value = "/video", produces = MediaType.APPLICATION_JSON_VALUE)
     public String uploadedVideoFilePart() {
         log.info("已上传的视频文件分片(待实现)");
-        return WebBody.failWithMsg("已上传的视频文件分片(待实现)");
+        return WebBody.success();
     }
 
     @ApiOperation(value = "上传视频分片文件")

+ 0 - 5
src/main/java/cn/reghao/dfs/store/db/mapper/ImageFileMapper.java

@@ -4,16 +4,11 @@ import cn.reghao.jutil.jdk.db.BaseMapper;
 import cn.reghao.dfs.store.model.po.ImageFile;
 import org.apache.ibatis.annotations.Mapper;
 
-import java.util.List;
-
 /**
  * @author reghao
  * @date 2021-12-08 14:41:35
  */
 @Mapper
 public interface ImageFileMapper extends BaseMapper<ImageFile> {
-    @Deprecated
-    void updateSetUrl(ImageFile imageFile);
-
     ImageFile findByImageFileId(String imageFileId);
 }

+ 36 - 3
src/main/java/cn/reghao/dfs/store/service/media/ImageFileService.java

@@ -5,12 +5,15 @@ import cn.reghao.dfs.store.model.dto.PathUrl;
 import cn.reghao.dfs.store.model.po.ImageFile;
 import cn.reghao.dfs.store.model.vo.ImageFileRet;
 import cn.reghao.dfs.store.model.dto.UploadedFile;
+import cn.reghao.dfs.store.service.FileUrlService;
 import cn.reghao.dfs.store.util.media.ImageOps;
 import cn.reghao.jutil.tool.id.IdGenerator;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
 import java.io.*;
 
 /**
@@ -20,16 +23,18 @@ import java.io.*;
 @Slf4j
 @Service
 public class ImageFileService {
+    private final FileUrlService fileUrlService;
     private final ImageFileMapper imageFileMapper;
     private final IdGenerator idGenerator;
 
-    public ImageFileService(ImageFileMapper imageFileMapper) {
+    public ImageFileService(FileUrlService fileUrlService, ImageFileMapper imageFileMapper) {
+        this.fileUrlService = fileUrlService;
         this.imageFileMapper = imageFileMapper;
         this.idGenerator = new IdGenerator("image-file-id");
     }
 
     @Transactional(rollbackFor = Exception.class)
-    public ImageFileRet process(UploadedFile uploadedFile) throws Exception {
+    public ImageFileRet process(UploadedFile uploadedFile, MediaResolution resolution) throws Exception {
         String fileId = uploadedFile.getFileId();
         PathUrl pathUrl = uploadedFile.getPathUrl();
         String filePath = pathUrl.getAbsolutePath();
@@ -44,6 +49,34 @@ public class ImageFileService {
         String imageFileId = idGenerator.getUuid();
         ImageFile imageFile = new ImageFile(imageFileId, fileId, horizontal, width, height, url);
         imageFileMapper.save(imageFile);
-        return new ImageFileRet(uploadedFile.getUploadId(), imageFileId, pathUrl.getUrl(), url);
+
+        String thumbnailUrl = String.format("%s@%s\\w_%s\\h", url, resolution.getWidth(), resolution.getHeight());
+        return new ImageFileRet(uploadedFile.getUploadId(), imageFileId, thumbnailUrl, url);
+    }
+
+    public InputStream getImageStream(String filePath, int reqWidth, int reqHeight) throws IOException {
+        // TODO 添加一层缓存
+        File file = new File(filePath);
+        ImageOps.Size imgSize = ImageOps.info(file);
+        int width = imgSize.getWidth();
+        int height = imgSize.getHeight();
+
+        MediaResolution quality = MediaQuality.getQuality(width, height);
+        MediaResolution reqQuality = MediaQuality.getQuality(reqWidth, reqHeight);
+        if (quality.getHeight() < reqQuality.getHeight()) {
+            return new FileInputStream(filePath);
+        }
+
+        int ratio;
+        if (width > height) {
+            ratio = quality.getHeight()/ reqQuality.getHeight();
+        } else {
+            ratio = quality.getWidth()/ reqQuality.getWidth();
+        }
+
+        BufferedImage bufferedImage = ImageOps.resize(filePath, ratio);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        ImageIO.write(bufferedImage, "jpg", baos);
+        return new ByteArrayInputStream(baos.toByteArray());
     }
 }

+ 1 - 30
src/main/java/cn/reghao/dfs/store/service/media/MediaQuality.java

@@ -12,36 +12,7 @@ public class MediaQuality {
      * @return
      * @date 2022-08-18 下午2:25
      */
-    public static String getQuality(int width, int height) {
-        boolean horizontal = width > height;
-        String currentQuality;
-        int currentAbs;
-        MediaResolution[] arr = MediaResolution.values();
-        if (horizontal) {
-            currentAbs = Math.abs(height-arr[0].getHeight());
-            currentQuality = arr[0].getQuality();
-            for (int i = 1; i < arr.length; i++) {
-                int currentAbs1 = Math.abs(height-arr[i].getHeight());
-                if (currentAbs1 < currentAbs) {
-                    currentAbs = currentAbs1;
-                    currentQuality = arr[i].getQuality();
-                }
-            }
-        } else {
-            currentAbs = Math.abs(width-arr[0].getWidth());
-            currentQuality = arr[0].getQuality();
-            for (int i = 1; i < arr.length; i++) {
-                int currentAbs1 = Math.abs(width-arr[i].getWidth());
-                if (currentAbs1 < currentAbs) {
-                    currentAbs = currentAbs1;
-                    currentQuality = arr[i].getQuality();
-                }
-            }
-        }
-        return currentQuality;
-    }
-
-    public static MediaResolution getQuality1(int width, int height) {
+    public static MediaResolution getQuality(int width, int height) {
         boolean horizontal = width > height;
         MediaResolution[] arr = MediaResolution.values();
         MediaResolution resolution = arr[0];

+ 6 - 4
src/main/java/cn/reghao/dfs/store/service/media/VideoFileService.java

@@ -90,18 +90,20 @@ public class VideoFileService {
         videoFile.setDuration(duration);
         videoFile.setHorizontal(horizontal);
         String videoFileId = videoFile.getVideoFileId();
-        String quality = MediaQuality.getQuality(width, height);
-        VideoUrl videoUrl = new VideoUrl(videoFileId, fileId, VideoUrlType.mp4.getName(), width, height, quality);
+        MediaResolution mediaResolution = MediaQuality.getQuality(width, height);
+        VideoUrl videoUrl = new VideoUrl(videoFileId, fileId, VideoUrlType.mp4.getName(),
+                width, height, mediaResolution.getQuality());
         videoUrlMapper.save(videoUrl);
     }
 
     @Transactional(rollbackFor = Exception.class)
-    public void setVideoCover(String videoFileId, UploadingFile uploadingFile) throws Exception {
+    public ImageFileRet setVideoCover(String videoFileId, UploadingFile uploadingFile) throws Exception {
         UploadedFile uploadedFile = fileUploadService.put(uploadingFile);
-        ImageFileRet imageFileRet = imageFileService.process(uploadedFile);
+        ImageFileRet imageFileRet = imageFileService.process(uploadedFile, MediaResolution.p144);
 
         String coverUrl = imageFileRet.getThumbnailUrl();
         String coverUrlOriginal = imageFileRet.getOriginalUrl();
         videoFileMapper.updateSetCover(videoFileId, coverUrl, coverUrlOriginal);
+        return imageFileRet;
     }
 }

+ 6 - 4
src/test/java/ConsistentCheckTest.java

@@ -7,6 +7,7 @@ import cn.reghao.dfs.store.model.dto.UploadedFile;
 import cn.reghao.dfs.store.service.FileUploadService;
 import cn.reghao.dfs.store.service.media.ImageFileService;
 import cn.reghao.dfs.store.service.media.MediaQuality;
+import cn.reghao.dfs.store.service.media.MediaResolution;
 import cn.reghao.jutil.jdk.http.util.UrlFormatter;
 import cn.reghao.dfs.store.DfsStoreApplication;
 import cn.reghao.jutil.tool.id.IdGenerator;
@@ -68,9 +69,9 @@ public class ConsistentCheckTest {
                 UploadingFile uploadingFile = new UploadingFile(filename, size, contentType, inputStream);
                 UploadedFile uploadedFile = fileUploadService.put(uploadingFile);
 
-                ImageFileRet imageFileRet = imageFileService.process(uploadedFile);
+                /*ImageFileRet imageFileRet = imageFileService.process(uploadedFile);
                 String imageFileId = imageFileRet.getImageFileId();
-                String url1 = imageFileRet.getThumbnailUrl();
+                String url1 = imageFileRet.getThumbnailUrl();*/
                 //saveFile(inputStream, new File(String.format("/home/reghao/Downloads/0/%s", filename)));
             } catch (Exception e) {
                 e.printStackTrace();
@@ -130,8 +131,9 @@ public class ConsistentCheckTest {
         String fileId = fileRet.getFileId();
         int width = 1280;
         int height = 720;
-        String quality = MediaQuality.getQuality(width, height);
-        VideoUrl videoUrl = new VideoUrl(videoFileId, fileId, VideoUrlType.mp4.getName(), width, height, quality);
+        MediaResolution mediaResolution = MediaQuality.getQuality(width, height);
+        VideoUrl videoUrl = new VideoUrl(videoFileId, fileId, VideoUrlType.mp4.getName(),
+                width, height, mediaResolution.getQuality());
         videoUrlMapper.save(videoUrl);
     }
 

+ 0 - 53
src/test/java/ImageFileTest.java

@@ -1,53 +0,0 @@
-import cn.reghao.dfs.store.service.media.MediaQuality;
-import cn.reghao.dfs.store.service.media.MediaResolution;
-import cn.reghao.dfs.store.util.media.ImageOps;
-import lombok.extern.slf4j.Slf4j;
-
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-
-/**
- * @author reghao
- * @date 2022-08-18 10:30:30
- */
-@Slf4j
-public class ImageFileTest {
-    static void test() throws IOException {
-        File dir = new File("/opt/file/disk0/spider/bili/img/vidcover/");
-        for (File file : dir.listFiles()) {
-            long length = file.length();
-            ImageOps.Size imgSize = ImageOps.info(file);
-            int width = imgSize.getWidth();
-            int height = imgSize.getHeight();
-            MediaResolution quality = MediaQuality.getQuality1(width, height);
-            int height1 = quality.getHeight();
-            int resHeight = MediaResolution.p360.getHeight();
-            if (height1 > resHeight) {
-                int ratio = height1/resHeight;
-                BufferedImage bufferedImage = ImageOps.resize(file.getAbsolutePath(), ratio);
-                ImageOps.saveImage(bufferedImage, "/home/reghao/Downloads/2.jpg");
-            }
-
-
-            System.out.println();
-        }
-    }
-
-    public static void main(String[] args) throws IOException {
-        String filePath = "/home/reghao/Downloads/0.jpg";
-        File file = new File(filePath);
-        ImageOps.Size imgSize = ImageOps.info(file);
-        int width = imgSize.getWidth();
-        int height = imgSize.getHeight();
-
-        MediaResolution quality = MediaQuality.getQuality1(width, height);
-        int height1 = quality.getHeight();
-        int resHeight = MediaResolution.p480.getHeight();
-        if (height1 > resHeight) {
-            int ratio = height1/resHeight;
-            BufferedImage bufferedImage = ImageOps.resize(file.getAbsolutePath(), ratio);
-            ImageOps.saveImage(bufferedImage, "/home/reghao/Downloads/3.jpg");
-        }
-    }
-}