From bf7a9ef439e3b49268974d564107999619b2b4fd Mon Sep 17 00:00:00 2001
From: rain <167982779@qq.com>
Date: Sat, 20 Jul 2024 09:28:40 +0800
Subject: [PATCH] 优化图片压缩下载使用多线程

---
 src/main/java/com/dji/sample/media/util/ImageDownloaderAndCompressor.java |  133 ++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 133 insertions(+), 0 deletions(-)

diff --git a/src/main/java/com/dji/sample/media/util/ImageDownloaderAndCompressor.java b/src/main/java/com/dji/sample/media/util/ImageDownloaderAndCompressor.java
new file mode 100644
index 0000000..3818a95
--- /dev/null
+++ b/src/main/java/com/dji/sample/media/util/ImageDownloaderAndCompressor.java
@@ -0,0 +1,133 @@
+package com.dji.sample.media.util;
+
+import java.awt.image.BufferedImage;
+import java.io.*;
+import java.net.URL;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+import javax.imageio.ImageIO;
+import javax.servlet.http.HttpServletResponse;
+
+public class ImageDownloaderAndCompressor {
+
+
+    private static final int THREAD_POOL_SIZE = 10;
+
+    public static void downloadAndSaveImages(List<String> urls, String outputFolder) {
+        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
+        CountDownLatch latch = new CountDownLatch(urls.size());
+        int count = 0;
+
+        for (String imageUrl : urls) {
+            final int index = count++;
+            executorService.submit(() -> {
+                try {
+                    // 下载图片
+                    URL url = new URL(imageUrl);
+                    BufferedImage image = ImageIO.read(url);
+                    // 保存图片
+                    File outputfile = new File(outputFolder, "image_" + index + ".jpg");
+                    ImageIO.write(image, "jpg", outputfile);
+                    System.out.println("Saved: " + outputfile.getAbsolutePath());
+                } catch (IOException e) {
+                    System.err.println("Failed to download image: " + imageUrl);
+                    e.printStackTrace();
+                } finally {
+                    latch.countDown();
+                }
+            });
+        }
+
+        try {
+            latch.await();
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            System.err.println("Image downloading was interrupted.");
+        } finally {
+            executorService.shutdown();
+        }
+    }
+
+    public static void zipAndSendFolder(String folderName, HttpServletResponse response) {
+        File zipFile = new File(folderName + ".zip");
+        try {
+            zipFolder(folderName, zipFile.getPath());
+
+            // 设置响应头
+            response.setContentType("application/zip");
+            response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getName());
+            response.setContentLength((int) zipFile.length());
+
+            // 将压缩文件写入响应
+            try (InputStream is = new FileInputStream(zipFile);
+                 OutputStream os = response.getOutputStream()) {
+                byte[] buffer = new byte[1024];
+                int length;
+                while ((length = is.read(buffer)) > 0) {
+                    os.write(buffer, 0, length);
+                }
+            }
+
+        } catch (IOException e) {
+            System.err.println("Failed to compress or send folder: " + folderName);
+            e.printStackTrace();
+            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            try {
+                response.getWriter().write("Failed to compress or send folder: " + folderName);
+            } catch (IOException ex) {
+                ex.printStackTrace();
+            }
+        } finally {
+            // 删除临时压缩文件
+            if (zipFile.exists()) {
+                zipFile.delete();
+            }
+        }
+    }
+
+    public static void zipFolder(String srcFolder, String destZipFile) throws IOException {
+        try (FileOutputStream fos = new FileOutputStream(destZipFile);
+             ZipOutputStream zos = new ZipOutputStream(fos)) {
+
+            File srcFile = new File(srcFolder);
+            for (File file : srcFile.listFiles()) {
+                try (FileInputStream fis = new FileInputStream(file)) {
+                    ZipEntry zipEntry = new ZipEntry(file.getName());
+                    zos.putNextEntry(zipEntry);
+
+                    byte[] bytes = new byte[1024];
+                    int length;
+                    while ((length = fis.read(bytes)) >= 0) {
+                        zos.write(bytes, 0, length);
+                    }
+                    zos.closeEntry();
+                }
+            }
+        }
+    }
+
+    public static void cleanUp(String folderName) {
+        File folder = new File(folderName);
+        deleteFolder(folder);
+    }
+
+    public static void deleteFolder(File folder) {
+        File[] files = folder.listFiles();
+        if (files != null) {
+            for (File f : files) {
+                if (f.isDirectory()) {
+                    deleteFolder(f);
+                } else {
+                    f.delete();
+                }
+            }
+        }
+        folder.delete();
+    }
+
+}
+

--
Gitblit v1.9.3