chenbiao 2 年之前
父节点
当前提交
276fe9af26

+ 6 - 0
midjourney/pom.xml

@@ -172,6 +172,12 @@
             <scope>provided</scope>
         </dependency>
 
+        <dependency>
+            <groupId>com.twelvemonkeys.imageio</groupId>
+            <artifactId>imageio-webp</artifactId>
+            <version>3.8.0</version>
+        </dependency>
+
 
     </dependencies>
 

+ 83 - 15
midjourney/src/main/java/com/yhlxj/service/midjourney/impl/MidjourneyServiceImpl.java

@@ -32,13 +32,18 @@ import com.yhlxj.service.common.EnvCommonService;
 import com.yhlxj.service.midjourney.MidjourneyAccountService;
 import com.yhlxj.service.midjourney.MidjourneyService;
 import com.yhlxj.web.wss.WssSession;
+import lombok.Data;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
 import javax.imageio.stream.FileImageOutputStream;
+import javax.imageio.stream.ImageInputStream;
+import java.awt.image.BufferedImage;
 import java.io.File;
 import java.io.IOException;
 import java.net.MalformedURLException;
@@ -46,6 +51,7 @@ import java.net.URL;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.stream.Collectors;
 
@@ -63,6 +69,8 @@ public class MidjourneyServiceImpl implements MidjourneyService {
     private static final String FAST_HOST = "https://aigc.api4midjourney.com/api";
     private static final String FAST_TOKEN = "14a6b469-7cb2-4b99-9238-676c7c5cffef";
 
+    private static final Map<Long, ImgSize> TASK_IMG_SIZE_MAP = new ConcurrentHashMap<>();
+
     private final MidjourneyUserConversationMapper conversationMapper;
 
     private static final List<String> progress = List.of("100%");
@@ -496,17 +504,17 @@ public class MidjourneyServiceImpl implements MidjourneyService {
                 }
                 conversation.setId(dbConversation.getId());
                 conversationMapper.updateById(conversation);
-                TASK_EXECUTOR.execute(() -> {
-                    try {
-                        String imageUrl = conversation.getImageUrl();
-                        if (StringUtil.isNotBlank(imageUrl)) {
-                            conversation.setImageUrl(uploadPic(imageUrl, "conversation"+dbConversation.getId()));
-                            conversationMapper.updateById(conversation);
-                        }
-                    } catch (IOException e) {
-                        log.error("上传图片失败",e);
-                    }
-                });
+                //TASK_EXECUTOR.execute(() -> {
+                //    try {
+                //        String imageUrl = conversation.getImageUrl();
+                //        if (StringUtil.isNotBlank(imageUrl)) {
+                //            conversation.setImageUrl(uploadPic(imageUrl, "conversation"+dbConversation.getId()));
+                //            conversationMapper.updateById(conversation);
+                //        }
+                //    } catch (IOException e) {
+                //        log.error("上传图片失败",e);
+                //    }
+                //});
                 //失败返还次数
                 if ("FAILURE".equals(conversation.getStatus())){
                     if (StringUtils.equals("未知频道",conversation.getFailReason())) {
@@ -609,18 +617,65 @@ public class MidjourneyServiceImpl implements MidjourneyService {
     }
 
     @Override
-    public void notifyHook(String json) throws MalformedURLException {
+    public void notifyHook(String json) throws IOException {
         log.info("notifyHook:{}", json);
         JSONObject jsons = JSONUtil.parseObj(json);
         MidjourneyUserConversation conversation = JSONUtil.toBean(jsons, MidjourneyUserConversation.class);
         conversation.setUserId(jsons.getLong("state"));
         conversation.setTaskId(jsons.getLong("id"));
         if (StringUtil.isNotBlank(conversation.getImageUrl())) {
+            log.info("获取到的图片 url:{}", conversation.getImageUrl());
+            ImgSize imgSize = TASK_IMG_SIZE_MAP.get(conversation.getTaskId());
             URL url = new URL(conversation.getImageUrl());
-            String scaling = "&quality=lossless&width=350&height=350";
-            if(url.getFile().contains("webp")){
-               scaling += "&format=webp";
+            url = new URL(url.getProtocol(), "cdn.mj.liuliangbang.vip", url.getPort(), url.getFile());
+            String filePath = url.getFile();
+            // 注册 WebP 插件
+            ImageIO.scanForPlugins();
+
+            // 从 URL 中读取图像,特别处理 WebP 格式
+            BufferedImage image = null;
+            if (filePath.contains("webp")) {
+                Iterator<ImageReader> readers = ImageIO.getImageReadersByMIMEType("image/webp");
+                if (readers.hasNext()) {
+                    ImageReader reader = readers.next();
+                    try (ImageInputStream iis = ImageIO.createImageInputStream(url.openStream())) {
+                        reader.setInput(iis, true);
+                        image = reader.read(0);
+                    }
+                }
+            } else {
+                image = ImageIO.read(url);
             }
+
+            if (image == null) {
+                throw new IOException("Failed to read image from URL: " + conversation.getImageUrl());
+            }
+
+            if (imgSize == null) {
+                try {
+                    //BufferedImage image = ImageIO.read(new URL(url.getProtocol(), "cdn.mj.liuliangbang.vip", url.getPort(), url.getFile()));
+                    // 获取图像的宽度和高度
+                    int width = image.getWidth();
+                    int height = image.getHeight();
+                    log.info("首次获取到的图片 尺寸:{},{}", width, height);
+                    // 缩小宽度和高度的一半
+                    imgSize = new ImgSize();
+                    imgSize.setHeight(height);
+                    imgSize.setWidth(width);
+                    TASK_IMG_SIZE_MAP.put(conversation.getTaskId(), imgSize);
+                }catch (Exception e){
+                    log.error("下载图获取尺寸错误,{}", StringUtil.getErrorText(e));
+                }
+            }
+
+            String scaling = "";
+            if(imgSize != null){
+                scaling = "quality=lossless&width=" + imgSize.getWidth() + "&height=" + imgSize.getHeight();
+                if(url.getFile().contains("webp")){
+                    scaling += "&format=webp";
+                }
+            }
+
             log.info("任务执行回调 imgUrl:{}", conversation.getImageUrl());
             // 使用 Hutool 提取各个部分并构建新 URL
             String newUrl = URLUtil.toURI(new URL(url.getProtocol(), "cdn.mj.liuliangbang.vip", url.getPort(), url.getFile() + scaling)).toString();
@@ -648,4 +703,17 @@ public class MidjourneyServiceImpl implements MidjourneyService {
             }
         });
     }
+
+    @Data
+    public class ImgSize{
+        /**
+         * 宽度
+         */
+        private Integer width;
+
+        /**
+         * 高度
+         */
+        private Integer height;
+    }
 }