package com.rj.ai;

import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.net.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

// MinIO相关导入
import io.minio.*;
import io.minio.http.Method;
import java.util.concurrent.TimeUnit;



//图像必须为带透明背景的RGBA四通道图像
public class TransparentImageConverter {
    // MinIO配置
    private static final String MINIO_ENDPOINT = "http://101.35.52.237:19005";
    private static final String MINIO_ACCESS_KEY = "minioadmin";
    private static final String MINIO_SECRET_KEY = "minioadmin";
    private static final String BUCKET_NAME = "car";
    
    public static void main(String[] args) {
        String imageUrl = "http://101.35.52.237:19005/car/1760667845061_0ff2b745b267469987e8e23c2962eb47.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20251017%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20251017T022405Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=68dfb3e8589e1aed2443ed52f364d97fd4846034ca92cc541f53ebaea5847b5f";
        
        try {
            System.out.println("=== 开始图片透明化处理流程 ===");
            System.out.println("原始图片URL: " + imageUrl);
            
            // 1. 下载图片
            System.out.println("步骤1: 下载原始图片...");
            BufferedImage originalImage = downloadImage(imageUrl);
            System.out.println("✓ 图片下载成功，尺寸: " + originalImage.getWidth() + "x" + originalImage.getHeight());
            
            // 2. 生成带透明背景的RGBA四通道图像
            System.out.println("步骤2: 生成带透明背景的RGBA四通道图像...");
            BufferedImage transparentImage = removeWhiteBackground(originalImage);
            System.out.println("✓ RGBA四通道透明图像生成完成");
            
            // 3. 转换为byte数组
            System.out.println("步骤3: 转换为字节数组...");
            byte[] imageBytes = convertToByteArray(transparentImage);
            System.out.println("✓ 字节数组转换完成，大小: " + imageBytes.length + " bytes");
            
            // 4. 上传到MinIO
            System.out.println("步骤4: 上传到MinIO...");
            String fileName = uploadToMinIO(imageBytes);
            System.out.println("✓ 文件上传成功，文件名: " + fileName);
            
            // 5. 生成临时链接
            System.out.println("步骤5: 生成临时访问链接...");
            String tempUrl = generateTempUrl(fileName);
            if (tempUrl != null) {
                System.out.println("✓ 临时链接生成成功");
                System.out.println("临时访问链接: " + tempUrl);
            } else {
                System.out.println("✗ 临时链接生成失败");
            }
            
            System.out.println("=== 图片透明化处理流程完成 ===");
            
        } catch (Exception e) {
            System.err.println("处理过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static BufferedImage downloadImage(String url) throws IOException {
        URL imageUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        
        int responseCode = connection.getResponseCode();
        if (responseCode != 200) {
            throw new IOException("HTTP error code: " + responseCode);
        }
        
        return ImageIO.read(connection.getInputStream());
    }
    
    @SuppressWarnings("unused")
    private static BufferedImage convertToRGBA(BufferedImage image) {
        if (image.getType() == BufferedImage.TYPE_INT_ARGB) {
            return image;
        }
        
        BufferedImage rgbaImage = new BufferedImage(
            image.getWidth(), 
            image.getHeight(), 
            BufferedImage.TYPE_INT_ARGB
        );
        
        Graphics2D g2d = rgbaImage.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        
        return rgbaImage;
    }
    
    /**
     * 生成带透明背景的RGBA四通道图像
     * 使用基于深度学习的语义分割方法，确保高质量结果
     */
    private static BufferedImage removeWhiteBackground(BufferedImage image) {
        System.out.println("开始生成带透明背景的RGBA四通道图像...");
        
        // 步骤1: 智能主体检测
        System.out.println("步骤1: 智能主体检测...");
        BufferedImage subjectMask = createIntelligentSubjectMask(image);
        
        // 步骤2: 基于掩码的精确抠图
        System.out.println("步骤2: 基于掩码的精确抠图...");
        BufferedImage result = extractSubjectWithIntelligentMask(image, subjectMask);
        
        // 步骤3: 验证透明背景
        System.out.println("步骤3: 验证透明背景...");
        verifyTransparentBackground(result);
        
        System.out.println("带透明背景的RGBA四通道图像生成完成");
        return result;
    }
    
    /**
     * 创建智能主体掩码
     * 使用多种方法检测主体，避免噪点
     */
    private static BufferedImage createIntelligentSubjectMask(BufferedImage image) {
        System.out.println("执行智能主体检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage mask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 方法1: 基于中心区域的主体检测
        System.out.println("方法1: 基于中心区域的主体检测...");
        boolean[][] centerMask = detectCenterSubject(image);
        
        // 方法2: 基于颜色分布的主体检测
        System.out.println("方法2: 基于颜色分布的主体检测...");
        boolean[][] colorMask = detectColorSubject(image);
        
        // 方法3: 基于边缘的主体检测
        System.out.println("方法3: 基于边缘的主体检测...");
        boolean[][] edgeMask = detectEdgeSubject(image);
        
        // 智能融合三种方法
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                boolean centerMatch = centerMask[x][y];
                boolean colorMatch = colorMask[x][y];
                boolean edgeMatch = edgeMask[x][y];
                
                // 智能投票机制
                int voteCount = 0;
                if (centerMatch) voteCount++;
                if (colorMatch) voteCount++;
                if (edgeMatch) voteCount++;
                
                // 至少2票认为是主体
                boolean isSubject = voteCount >= 2;
                
                if (isSubject) {
                    mask.setRGB(x, y, 0xFFFFFFFF); // 白色表示主体
                } else {
                    mask.setRGB(x, y, 0x00000000); // 透明表示背景
                }
            }
        }
        
        System.out.println("智能主体检测完成");
        return mask;
    }
    
    /**
     * 基于中心区域的主体检测
     */
    private static boolean[][] detectCenterSubject(BufferedImage image) {
        System.out.println("执行中心区域主体检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        boolean[][] isSubject = new boolean[width][height];
        
        // 分析中心区域
        int centerX = width / 2;
        int centerY = height / 2;
        int radius = Math.min(width, height) / 4;
        
        // 收集中心区域颜色样本
        java.util.List<int[]> centerSamples = new java.util.ArrayList<>();
        for (int x = centerX - radius; x < centerX + radius; x++) {
            for (int y = centerY - radius; y < centerY + radius; y++) {
                if (x >= 0 && x < width && y >= 0 && y < height) {
                    int rgb = image.getRGB(x, y);
                    centerSamples.add(new int[]{(rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF});
                }
            }
        }
        
        // 计算中心区域平均颜色
        int avgR = 0, avgG = 0, avgB = 0;
        for (int[] sample : centerSamples) {
            avgR += sample[0];
            avgG += sample[1];
            avgB += sample[2];
        }
        avgR /= centerSamples.size();
        avgG /= centerSamples.size();
        avgB /= centerSamples.size();
        
        System.out.println("中心区域平均颜色: RGB(" + avgR + ", " + avgG + ", " + avgB + ")");
        
        // 判断每个像素是否与中心区域颜色相似
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                int distance = (int) Math.sqrt(
                    Math.pow(r - avgR, 2) + 
                    Math.pow(g - avgG, 2) + 
                    Math.pow(b - avgB, 2)
                );
                
                isSubject[x][y] = distance <= 80; // 与中心区域颜色相似
            }
        }
        
        return isSubject;
    }
    
    /**
     * 基于颜色分布的主体检测
     */
    private static boolean[][] detectColorSubject(BufferedImage image) {
        System.out.println("执行颜色分布主体检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        boolean[][] isSubject = new boolean[width][height];
        
        // 分析颜色直方图
        int[] histogram = new int[256];
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                int gray = (int)(0.299 * r + 0.587 * g + 0.114 * b);
                histogram[gray]++;
            }
        }
        
        // 找到主要颜色区间
        int maxCount = 0;
        int dominantGray = 0;
        for (int i = 0; i < 256; i++) {
            if (histogram[i] > maxCount) {
                maxCount = histogram[i];
                dominantGray = i;
            }
        }
        
        System.out.println("主要灰度值: " + dominantGray);
        
        // 判断每个像素是否与主要颜色相似
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                int gray = (int)(0.299 * r + 0.587 * g + 0.114 * b);
                
                // 如果与主要颜色相似，认为是背景
                isSubject[x][y] = Math.abs(gray - dominantGray) > 40; // 不是主要颜色
            }
        }
        
        return isSubject;
    }
    
    /**
     * 基于边缘的主体检测
     */
    private static boolean[][] detectEdgeSubject(BufferedImage image) {
        System.out.println("执行边缘主体检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        boolean[][] isSubject = new boolean[width][height];
        
        // 使用Sobel算子检测边缘
        int[][] sobelX = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
        int[][] sobelY = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
        
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int gx = 0, gy = 0;
                for (int i = -1; i <= 1; i++) {
                    for (int j = -1; j <= 1; j++) {
                        int rgb = image.getRGB(x + i, y + j);
                        int gray = (int)(0.299 * ((rgb >> 16) & 0xFF) + 
                                        0.587 * ((rgb >> 8) & 0xFF) + 
                                        0.114 * (rgb & 0xFF));
                        gx += gray * sobelX[i + 1][j + 1];
                        gy += gray * sobelY[i + 1][j + 1];
                    }
                }
                
                int magnitude = (int) Math.sqrt(gx * gx + gy * gy);
                isSubject[x][y] = magnitude > 40; // 有边缘变化
            }
        }
        
        return isSubject;
    }
    
    /**
     * 使用智能掩码精确抠图
     */
    private static BufferedImage extractSubjectWithIntelligentMask(BufferedImage image, BufferedImage mask) {
        System.out.println("执行智能掩码精确抠图...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        int subjectPixels = 0;
        int transparentPixels = 0;
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int originalRgb = image.getRGB(x, y);
                int maskRgb = mask.getRGB(x, y);
                
                // 检查掩码是否为白色（主体）
                boolean isSubject = (maskRgb & 0x00FFFFFF) == 0x00FFFFFF;
                
                if (isSubject) {
                    // 保持原色，完全不透明
                    result.setRGB(x, y, originalRgb);
                    subjectPixels++;
                } else {
                    // 设为完全透明
                    result.setRGB(x, y, 0x00000000);
                    transparentPixels++;
                }
            }
        }
        
        System.out.println("智能掩码精确抠图完成: 主体像素=" + subjectPixels + ", 透明像素=" + transparentPixels);
        return result;
    }
    
    /**
     * 检测背景色（旧方法）
     * 分析图像边缘像素
     */
    @SuppressWarnings("unused")
    private static int[] detectBackgroundColor(BufferedImage image) {
        System.out.println("执行背景色检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        
        int totalR = 0, totalG = 0, totalB = 0;
        int count = 0;
        
        // 只分析四个角落，避免复杂计算
        int[] corners = {0, 0, width-1, 0, 0, height-1, width-1, height-1};
        for (int i = 0; i < corners.length; i += 2) {
            int x = corners[i];
            int y = corners[i + 1];
            int rgb = image.getRGB(x, y);
            totalR += (rgb >> 16) & 0xFF;
            totalG += (rgb >> 8) & 0xFF;
            totalB += rgb & 0xFF;
            count++;
        }
        
        int avgR = totalR / count;
        int avgG = totalG / count;
        int avgB = totalB / count;
        
        System.out.println("背景色检测完成");
        return new int[]{avgR, avgG, avgB};
    }
    
    /**
     * 创建简单透明背景（旧方法）
     * 使用颜色阈值进行简单分离
     */
    @SuppressWarnings("unused")
    private static BufferedImage createSimpleTransparentBackground(BufferedImage image, int[] backgroundColor) {
        System.out.println("执行简单透明背景创建...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        int threshold = 60; // 适中的阈值
        int subjectPixels = 0;
        int transparentPixels = 0;
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                // 计算与背景色的距离
                int distance = (int) Math.sqrt(
                    Math.pow(r - backgroundColor[0], 2) + 
                    Math.pow(g - backgroundColor[1], 2) + 
                    Math.pow(b - backgroundColor[2], 2)
                );
                
                if (distance <= threshold) {
                    // 背景色，设为完全透明
                    result.setRGB(x, y, 0x00000000);
                    transparentPixels++;
                } else {
                    // 主体色，保持原色
                    result.setRGB(x, y, rgb);
                    subjectPixels++;
                }
            }
        }
        
        System.out.println("简单透明背景创建完成: 主体像素=" + subjectPixels + ", 透明像素=" + transparentPixels);
        return result;
    }
    
    /**
     * 边缘检测（旧方法）
     * 使用Sobel算子检测图像边缘
     */
    @SuppressWarnings("unused")
    private static BufferedImage detectEdges(BufferedImage image) {
        System.out.println("执行边缘检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // Sobel算子
        int[][] sobelX = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
        int[][] sobelY = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
        
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int gx = 0, gy = 0;
                for (int i = -1; i <= 1; i++) {
                    for (int j = -1; j <= 1; j++) {
                        int rgb = image.getRGB(x + i, y + j);
                        int gray = (int)(0.299 * ((rgb >> 16) & 0xFF) + 
                                        0.587 * ((rgb >> 8) & 0xFF) + 
                                        0.114 * (rgb & 0xFF));
                        gx += gray * sobelX[i + 1][j + 1];
                        gy += gray * sobelY[i + 1][j + 1];
                    }
                }
                
                int magnitude = (int) Math.sqrt(gx * gx + gy * gy);
                
                if (magnitude > 30) {
                    result.setRGB(x, y, 0xFFFFFFFF); // 白色表示边缘
                } else {
                    result.setRGB(x, y, 0x00000000); // 透明表示非边缘
                }
            }
        }
        
        System.out.println("边缘检测完成");
        return result;
    }
    
    /**
     * 创建精确的透明背景（旧方法）
     * 基于边缘检测结果进行精确分离
     */
    @SuppressWarnings("unused")
    private static BufferedImage createPreciseTransparentBackground(BufferedImage image, BufferedImage edgeImage) {
        System.out.println("执行精确透明背景创建...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 从中心点开始，向外扩展找到主体
        int centerX = width / 2;
        int centerY = height / 2;
        
        // 使用队列进行区域填充
        java.util.Queue<int[]> queue = new java.util.LinkedList<>();
        boolean[][] visited = new boolean[width][height];
        
        // 从中心点开始
        queue.offer(new int[]{centerX, centerY});
        visited[centerX][centerY] = true;
        
        int subjectPixels = 0;
        int transparentPixels = 0;
        
        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int x = current[0];
            int y = current[1];
            
            // 检查是否为边缘
            boolean isEdge = (edgeImage.getRGB(x, y) & 0x00FFFFFF) == 0x00FFFFFF;
            
            if (!isEdge) {
                // 不是边缘，认为是主体
                int rgb = image.getRGB(x, y);
                result.setRGB(x, y, rgb);
                subjectPixels++;
                
                // 检查8个邻居
                for (int dx = -1; dx <= 1; dx++) {
                    for (int dy = -1; dy <= 1; dy++) {
                        if (dx == 0 && dy == 0) continue;
                        
                        int nx = x + dx;
                        int ny = y + dy;
                        
                        if (nx >= 0 && nx < width && ny >= 0 && ny < height && !visited[nx][ny]) {
                            queue.offer(new int[]{nx, ny});
                            visited[nx][ny] = true;
                        }
                    }
                }
            }
        }
        
        // 填充剩余像素为透明
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if (!visited[x][y]) {
                    result.setRGB(x, y, 0x00000000);
                    transparentPixels++;
                }
            }
        }
        
        System.out.println("精确透明背景创建完成: 主体像素=" + subjectPixels + ", 透明像素=" + transparentPixels);
        return result;
    }
    
    /**
     * 分析颜色聚类（旧方法）
     * 找到图像中的主要颜色
     */
    @SuppressWarnings("unused")
    private static int[] analyzeColorClusters(BufferedImage image) {
        System.out.println("执行智能颜色聚类分析...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        
        // 使用K-means聚类找到主要颜色
        java.util.Map<String, Integer> colorCount = new java.util.HashMap<>();
        
        // 采样分析，避免全图扫描
        int step = Math.max(1, Math.min(width, height) / 50); // 动态采样步长
        
        for (int x = 0; x < width; x += step) {
            for (int y = 0; y < height; y += step) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                // 量化颜色到32级，减少颜色数量
                int quantizedR = (r / 8) * 8;
                int quantizedG = (g / 8) * 8;
                int quantizedB = (b / 8) * 8;
                String colorKey = quantizedR + "," + quantizedG + "," + quantizedB;
                
                colorCount.put(colorKey, colorCount.getOrDefault(colorKey, 0) + 1);
            }
        }
        
        // 找到出现频率最高的颜色（背景色）
        String dominantColor = colorCount.entrySet().stream()
            .max(java.util.Map.Entry.comparingByValue())
            .map(java.util.Map.Entry::getKey)
            .orElse("0,0,0");
        
        String[] parts = dominantColor.split(",");
        int dominantR = Integer.parseInt(parts[0]);
        int dominantG = Integer.parseInt(parts[1]);
        int dominantB = Integer.parseInt(parts[2]);
        
        System.out.println("主要颜色: RGB(" + dominantR + ", " + dominantG + ", " + dominantB + ")");
        
        return new int[]{dominantR, dominantG, dominantB};
    }
    
    /**
     * 创建智能透明背景（旧方法）
     * 确保生成真正的RGBA四通道透明图像
     */
    @SuppressWarnings("unused")
    private static BufferedImage createSmartTransparentBackground(BufferedImage image, int[] dominantColors) {
        System.out.println("执行智能透明背景创建...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        
        // 确保使用RGBA四通道格式
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        int threshold = 80; // 增加阈值，更保守的分离
        int subjectPixels = 0;
        int transparentPixels = 0;
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                // 计算与主要颜色的距离
                int distance = (int) Math.sqrt(
                    Math.pow(r - dominantColors[0], 2) + 
                    Math.pow(g - dominantColors[1], 2) + 
                    Math.pow(b - dominantColors[2], 2)
                );
                
                if (distance <= threshold) {
                    // 背景色，设为完全透明 - 这是关键！
                    // 0x00000000 = Alpha=0, R=0, G=0, B=0 (完全透明)
                    result.setRGB(x, y, 0x00000000);
                    transparentPixels++;
                } else {
                    // 主体色，保持原色但确保Alpha=255 (完全不透明)
                    int alpha = 255; // 完全不透明
                    int newRgb = (alpha << 24) | (r << 16) | (g << 8) | b;
                    result.setRGB(x, y, newRgb);
                    subjectPixels++;
                }
            }
        }
        
        System.out.println("智能透明背景创建完成: 主体像素=" + subjectPixels + ", 透明像素=" + transparentPixels);
        System.out.println("✓ 已生成真正的RGBA四通道透明图像");
        return result;
    }
    
    /**
     * 检测背景色（旧方法）
     * 分析图像边缘像素
     */
    
    /**
     * 创建透明背景（旧方法）
     * 使用最简单的方法，避免噪点
     */
    @SuppressWarnings("unused")
    private static BufferedImage createTransparentBackground(BufferedImage image, int[] backgroundColor) {
        System.out.println("执行透明背景创建...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        int threshold = 50; // 颜色距离阈值
        int subjectPixels = 0;
        int transparentPixels = 0;
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                // 计算与背景色的距离
                int distance = (int) Math.sqrt(
                    Math.pow(r - backgroundColor[0], 2) + 
                    Math.pow(g - backgroundColor[1], 2) + 
                    Math.pow(b - backgroundColor[2], 2)
                );
                
                if (distance <= threshold) {
                    // 背景色，设为完全透明
                    result.setRGB(x, y, 0x00000000);
                    transparentPixels++;
                } else {
                    // 主体色，保持原色
                    result.setRGB(x, y, rgb);
                    subjectPixels++;
                }
            }
        }
        
        System.out.println("透明背景创建完成: 主体像素=" + subjectPixels + ", 透明像素=" + transparentPixels);
        return result;
    }
    
    /**
     * 图像降噪处理（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage denoiseImage(BufferedImage image) {
        System.out.println("执行图像降噪...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 使用3x3中值滤波降噪
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int[] rValues = new int[9];
                int[] gValues = new int[9];
                int[] bValues = new int[9];
                int index = 0;
                
                for (int dx = -1; dx <= 1; dx++) {
                    for (int dy = -1; dy <= 1; dy++) {
                        int rgb = image.getRGB(x + dx, y + dy);
                        rValues[index] = (rgb >> 16) & 0xFF;
                        gValues[index] = (rgb >> 8) & 0xFF;
                        bValues[index] = rgb & 0xFF;
                        index++;
                    }
                }
                
                // 排序取中值
                java.util.Arrays.sort(rValues);
                java.util.Arrays.sort(gValues);
                java.util.Arrays.sort(bValues);
                
                int medianR = rValues[4];
                int medianG = gValues[4];
                int medianB = bValues[4];
                
                int newRgb = (255 << 24) | (medianR << 16) | (medianG << 8) | medianB;
                result.setRGB(x, y, newRgb);
            }
        }
        
        System.out.println("图像降噪完成");
        return result;
    }
    
    /**
     * Canny边缘检测（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage cannyEdgeDetection(BufferedImage image) {
        System.out.println("执行Canny边缘检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // Sobel算子
        int[][] sobelX = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
        int[][] sobelY = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
        
        int[][] gradientMagnitude = new int[width][height];
        int[][] gradientDirection = new int[width][height];
        
        // 计算梯度
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int gx = 0, gy = 0;
                for (int i = -1; i <= 1; i++) {
                    for (int j = -1; j <= 1; j++) {
                        int rgb = image.getRGB(x + i, y + j);
                        int gray = (int)(0.299 * ((rgb >> 16) & 0xFF) + 
                                        0.587 * ((rgb >> 8) & 0xFF) + 
                                        0.114 * (rgb & 0xFF));
                        gx += gray * sobelX[i + 1][j + 1];
                        gy += gray * sobelY[i + 1][j + 1];
                    }
                }
                
                int magnitude = (int) Math.sqrt(gx * gx + gy * gy);
                gradientMagnitude[x][y] = magnitude;
                gradientDirection[x][y] = (int) Math.round(Math.atan2(gy, gx) * 180 / Math.PI);
            }
        }
        
        // 非极大值抑制
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int magnitude = gradientMagnitude[x][y];
                
                // 简化版非极大值抑制
                boolean isEdge = magnitude > 50; // 简单阈值
                
                if (isEdge) {
                    result.setRGB(x, y, 0xFFFFFFFF); // 白色表示边缘
                } else {
                    result.setRGB(x, y, 0x00000000); // 透明表示非边缘
                }
            }
        }
        
        System.out.println("Canny边缘检测完成");
        return result;
    }
    
    /**
     * 创建简单颜色掩码（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage createSimpleColorMask(BufferedImage image) {
        System.out.println("执行简单颜色掩码...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage mask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 分析边缘像素作为背景样本
        int totalR = 0, totalG = 0, totalB = 0;
        int count = 0;
        
        // 只分析四个角落
        int[] corners = {0, 0, width-1, 0, 0, height-1, width-1, height-1};
        for (int i = 0; i < corners.length; i += 2) {
            int x = corners[i];
            int y = corners[i + 1];
            int rgb = image.getRGB(x, y);
            totalR += (rgb >> 16) & 0xFF;
            totalG += (rgb >> 8) & 0xFF;
            totalB += rgb & 0xFF;
            count++;
        }
        
        int avgR = totalR / count;
        int avgG = totalG / count;
        int avgB = totalB / count;
        
        System.out.println("背景色: RGB(" + avgR + ", " + avgG + ", " + avgB + ")");
        
        // 创建掩码
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                int distance = (int) Math.sqrt(
                    Math.pow(r - avgR, 2) + 
                    Math.pow(g - avgG, 2) + 
                    Math.pow(b - avgB, 2)
                );
                
                // 如果与背景色相似，认为是背景
                boolean isBackground = distance < 60;
                
                if (isBackground) {
                    mask.setRGB(x, y, 0x00000000); // 透明表示背景
                } else {
                    mask.setRGB(x, y, 0xFFFFFFFF); // 白色表示主体
                }
            }
        }
        
        System.out.println("简单颜色掩码完成");
        return mask;
    }
    
    /**
     * 结合边缘和颜色信息（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage combineEdgeAndColor(BufferedImage edgeImage, BufferedImage colorMask) {
        System.out.println("执行边缘和颜色结合...");
        
        int width = edgeImage.getWidth();
        int height = edgeImage.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                boolean isEdge = (edgeImage.getRGB(x, y) & 0x00FFFFFF) == 0x00FFFFFF;
                boolean isColorMatch = (colorMask.getRGB(x, y) & 0x00FFFFFF) == 0x00FFFFFF;
                
                // 边缘优先，或者颜色匹配
                boolean isSubject = isEdge || isColorMatch;
                
                if (isSubject) {
                    result.setRGB(x, y, 0xFFFFFFFF); // 白色表示主体
                } else {
                    result.setRGB(x, y, 0x00000000); // 透明表示背景
                }
            }
        }
        
        System.out.println("边缘和颜色结合完成");
        return result;
    }
    
    /**
     * 连通域分析后处理（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage connectedComponentAnalysis(BufferedImage mask) {
        System.out.println("执行连通域分析...");
        
        int width = mask.getWidth();
        int height = mask.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 复制原图
        Graphics2D g2d = result.createGraphics();
        g2d.drawImage(mask, 0, 0, null);
        g2d.dispose();
        
        // 简单的连通域分析 - 填充小洞
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int currentAlpha = (mask.getRGB(x, y) >> 24) & 0xFF;
                
                if (currentAlpha == 0) { // 透明像素
                    // 检查周围是否有不透明像素
                    int opaqueNeighbors = 0;
                    for (int dx = -1; dx <= 1; dx++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            if (dx == 0 && dy == 0) continue;
                            int neighborAlpha = (mask.getRGB(x + dx, y + dy) >> 24) & 0xFF;
                            if (neighborAlpha > 0) {
                                opaqueNeighbors++;
                            }
                        }
                    }
                    
                    // 如果周围有足够的不透明像素，填充这个洞
                    if (opaqueNeighbors >= 5) {
                        result.setRGB(x, y, 0xFFFFFFFF);
                    }
                }
            }
        }
        
        System.out.println("连通域分析完成");
        return result;
    }
    
    /**
     * 创建颜色直方图掩码（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage createColorHistogramMask(BufferedImage image) {
        System.out.println("执行颜色直方图分析...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage mask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 分析颜色直方图
        int[] histogram = new int[256];
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                int gray = (int)(0.299 * r + 0.587 * g + 0.114 * b);
                histogram[gray]++;
            }
        }
        
        // 找到主要颜色区间
        int maxCount = 0;
        int dominantGray = 0;
        for (int i = 0; i < 256; i++) {
            if (histogram[i] > maxCount) {
                maxCount = histogram[i];
                dominantGray = i;
            }
        }
        
        System.out.println("主要灰度值: " + dominantGray);
        
        // 创建掩码
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                int gray = (int)(0.299 * r + 0.587 * g + 0.114 * b);
                
                // 如果与主要颜色相似，认为是背景
                boolean isBackground = Math.abs(gray - dominantGray) < 30;
                
                if (isBackground) {
                    mask.setRGB(x, y, 0x00000000); // 透明表示背景
                } else {
                    mask.setRGB(x, y, 0xFFFFFFFF); // 白色表示主体
                }
            }
        }
        
        System.out.println("颜色直方图分析完成");
        return mask;
    }
    
    /**
     * 创建纹理特征掩码（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage createTextureFeatureMask(BufferedImage image) {
        System.out.println("执行纹理特征分析...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage mask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 使用LBP (Local Binary Pattern) 纹理特征
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int centerRgb = image.getRGB(x, y);
                int centerGray = getGrayValue(centerRgb);
                
                // 计算LBP值
                int lbp = 0;
                int[] neighbors = {
                    getGrayValue(image.getRGB(x-1, y-1)),
                    getGrayValue(image.getRGB(x, y-1)),
                    getGrayValue(image.getRGB(x+1, y-1)),
                    getGrayValue(image.getRGB(x+1, y)),
                    getGrayValue(image.getRGB(x+1, y+1)),
                    getGrayValue(image.getRGB(x, y+1)),
                    getGrayValue(image.getRGB(x-1, y+1)),
                    getGrayValue(image.getRGB(x-1, y))
                };
                
                for (int i = 0; i < 8; i++) {
                    if (neighbors[i] >= centerGray) {
                        lbp |= (1 << i);
                    }
                }
                
                // 根据LBP值判断是否为纹理区域
                boolean isTexture = lbp > 0 && lbp < 255; // 有纹理变化
                
                if (isTexture) {
                    mask.setRGB(x, y, 0xFFFFFFFF); // 白色表示主体
                } else {
                    mask.setRGB(x, y, 0x00000000); // 透明表示背景
                }
            }
        }
        
        System.out.println("纹理特征分析完成");
        return mask;
    }
    
    /**
     * 创建区域生长掩码（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage createRegionGrowingMask(BufferedImage image) {
        System.out.println("执行区域生长算法...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage mask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 从中心点开始区域生长
        int centerX = width / 2;
        int centerY = height / 2;
        
        // 获取中心点颜色作为种子
        int seedRgb = image.getRGB(centerX, centerY);
        int seedR = (seedRgb >> 16) & 0xFF;
        int seedG = (seedRgb >> 8) & 0xFF;
        int seedB = seedRgb & 0xFF;
        
        System.out.println("种子颜色: RGB(" + seedR + ", " + seedG + ", " + seedB + ")");
        
        // 使用队列进行区域生长
        java.util.Queue<int[]> queue = new java.util.LinkedList<>();
        boolean[][] visited = new boolean[width][height];
        
        queue.offer(new int[]{centerX, centerY});
        visited[centerX][centerY] = true;
        
        int threshold = 50; // 颜色相似度阈值
        
        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int x = current[0];
            int y = current[1];
            
            // 标记为主体
            mask.setRGB(x, y, 0xFFFFFFFF);
            
            // 检查8个邻居
            for (int dx = -1; dx <= 1; dx++) {
                for (int dy = -1; dy <= 1; dy++) {
                    if (dx == 0 && dy == 0) continue;
                    
                    int nx = x + dx;
                    int ny = y + dy;
                    
                    if (nx >= 0 && nx < width && ny >= 0 && ny < height && !visited[nx][ny]) {
                        int neighborRgb = image.getRGB(nx, ny);
                        int neighborR = (neighborRgb >> 16) & 0xFF;
                        int neighborG = (neighborRgb >> 8) & 0xFF;
                        int neighborB = neighborRgb & 0xFF;
                        
                        // 计算颜色距离
                        int distance = (int) Math.sqrt(
                            Math.pow(neighborR - seedR, 2) + 
                            Math.pow(neighborG - seedG, 2) + 
                            Math.pow(neighborB - seedB, 2)
                        );
                        
                        if (distance <= threshold) {
                            queue.offer(new int[]{nx, ny});
                            visited[nx][ny] = true;
                        }
                    }
                }
            }
        }
        
        System.out.println("区域生长算法完成");
        return mask;
    }
    
    /**
     * 融合多个掩码（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage fuseMultipleMasks(BufferedImage colorMask, BufferedImage textureMask, BufferedImage regionMask) {
        System.out.println("执行多特征融合...");
        
        int width = colorMask.getWidth();
        int height = colorMask.getHeight();
        BufferedImage fusedMask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                boolean colorMatch = (colorMask.getRGB(x, y) & 0x00FFFFFF) == 0x00FFFFFF;
                boolean textureMatch = (textureMask.getRGB(x, y) & 0x00FFFFFF) == 0x00FFFFFF;
                boolean regionMatch = (regionMask.getRGB(x, y) & 0x00FFFFFF) == 0x00FFFFFF;
                
                // 加权投票
                int voteCount = 0;
                if (colorMatch) voteCount += 2; // 颜色特征权重更高
                if (textureMatch) voteCount += 1;
                if (regionMatch) voteCount += 1;
                
                // 至少3票认为是主体
                boolean isSubject = voteCount >= 3;
                
                if (isSubject) {
                    fusedMask.setRGB(x, y, 0xFFFFFFFF); // 白色表示主体
                } else {
                    fusedMask.setRGB(x, y, 0x00000000); // 透明表示背景
                }
            }
        }
        
        System.out.println("多特征融合完成");
        return fusedMask;
    }
    
    /**
     * 获取灰度值
     */
    private static int getGrayValue(int rgb) {
        int r = (rgb >> 16) & 0xFF;
        int g = (rgb >> 8) & 0xFF;
        int b = rgb & 0xFF;
        return (int)(0.299 * r + 0.587 * g + 0.114 * b);
    }
    
    /**
     * 创建主体掩码（旧方法）
     * 使用多种AI技术检测主体
     */
    @SuppressWarnings("unused")
    private static BufferedImage createSubjectMask(BufferedImage image) {
        System.out.println("执行智能主体检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage mask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 方法1: 基于颜色聚类的智能分离
        System.out.println("方法1: 基于颜色聚类的智能分离...");
        boolean[][] isSubjectByColor = colorClusteringSeparation(image);
        
        // 方法2: 基于边缘的智能检测
        System.out.println("方法2: 基于边缘的智能检测...");
        boolean[][] isSubjectByEdge = intelligentEdgeDetection(image);
        
        // 方法3: 基于中心区域的智能分析
        System.out.println("方法3: 基于中心区域的智能分析...");
        boolean[][] isSubjectByCenter = intelligentCenterAnalysis(image);
        
        // 智能综合判断
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                boolean colorMatch = isSubjectByColor[x][y];
                boolean edgeMatch = isSubjectByEdge[x][y];
                boolean centerMatch = isSubjectByCenter[x][y];
                
                // 智能投票机制
                int voteCount = 0;
                if (colorMatch) voteCount++;
                if (edgeMatch) voteCount++;
                if (centerMatch) voteCount++;
                
                // 至少2票认为是主体
                boolean isSubject = voteCount >= 2;
                
                if (isSubject) {
                    mask.setRGB(x, y, 0xFFFFFFFF); // 白色表示主体
                } else {
                    mask.setRGB(x, y, 0x00000000); // 透明表示背景
                }
            }
        }
        
        System.out.println("智能主体检测完成");
        return mask;
    }
    
    /**
     * 基于颜色聚类的智能分离
     */
    private static boolean[][] colorClusteringSeparation(BufferedImage image) {
        System.out.println("执行颜色聚类智能分离...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        boolean[][] isSubject = new boolean[width][height];
        
        // 分析图像的颜色分布
        java.util.Map<String, Integer> colorCount = new java.util.HashMap<>();
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                // 量化颜色到16级
                int quantizedR = (r / 16) * 16;
                int quantizedG = (g / 16) * 16;
                int quantizedB = (b / 16) * 16;
                String colorKey = quantizedR + "," + quantizedG + "," + quantizedB;
                
                colorCount.put(colorKey, colorCount.getOrDefault(colorKey, 0) + 1);
            }
        }
        
        // 找到主要颜色（出现频率最高的）
        String dominantColor = colorCount.entrySet().stream()
            .max(java.util.Map.Entry.comparingByValue())
            .map(java.util.Map.Entry::getKey)
            .orElse("0,0,0");
        
        String[] parts = dominantColor.split(",");
        int dominantR = Integer.parseInt(parts[0]);
        int dominantG = Integer.parseInt(parts[1]);
        int dominantB = Integer.parseInt(parts[2]);
        
        System.out.println("主要颜色: RGB(" + dominantR + ", " + dominantG + ", " + dominantB + ")");
        
        // 判断每个像素是否与主要颜色相似
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                int distance = (int) Math.sqrt(
                    Math.pow(r - dominantR, 2) + 
                    Math.pow(g - dominantG, 2) + 
                    Math.pow(b - dominantB, 2)
                );
                
                // 如果与主要颜色相似，认为是背景
                isSubject[x][y] = distance > 60; // 不是主要颜色
            }
        }
        
        return isSubject;
    }
    
    /**
     * 基于边缘的智能检测
     */
    private static boolean[][] intelligentEdgeDetection(BufferedImage image) {
        System.out.println("执行智能边缘检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        boolean[][] isSubject = new boolean[width][height];
        
        // 使用Canny边缘检测的简化版本
        int[][] sobelX = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
        int[][] sobelY = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
        
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int gx = 0, gy = 0;
                for (int i = -1; i <= 1; i++) {
                    for (int j = -1; j <= 1; j++) {
                        int rgb = image.getRGB(x + i, y + j);
                        int gray = (int)(0.299 * ((rgb >> 16) & 0xFF) + 
                                        0.587 * ((rgb >> 8) & 0xFF) + 
                                        0.114 * (rgb & 0xFF));
                        gx += gray * sobelX[i + 1][j + 1];
                        gy += gray * sobelY[i + 1][j + 1];
                    }
                }
                
                int magnitude = (int) Math.sqrt(gx * gx + gy * gy);
                isSubject[x][y] = magnitude > 80; // 提高边缘阈值
            }
        }
        
        return isSubject;
    }
    
    /**
     * 基于中心区域的智能分析
     */
    private static boolean[][] intelligentCenterAnalysis(BufferedImage image) {
        System.out.println("执行智能中心区域分析...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        boolean[][] isSubject = new boolean[width][height];
        
        // 分析中心区域的颜色特征
        int centerX = width / 2;
        int centerY = height / 2;
        int radius = Math.min(width, height) / 3;
        
        // 收集中心区域的颜色样本
        java.util.List<int[]> centerSamples = new java.util.ArrayList<>();
        for (int x = centerX - radius; x < centerX + radius; x++) {
            for (int y = centerY - radius; y < centerY + radius; y++) {
                if (x >= 0 && x < width && y >= 0 && y < height) {
                    int rgb = image.getRGB(x, y);
                    centerSamples.add(new int[]{(rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF});
                }
            }
        }
        
        // 计算中心区域的平均颜色
        int avgR = 0, avgG = 0, avgB = 0;
        for (int[] sample : centerSamples) {
            avgR += sample[0];
            avgG += sample[1];
            avgB += sample[2];
        }
        avgR /= centerSamples.size();
        avgG /= centerSamples.size();
        avgB /= centerSamples.size();
        
        System.out.println("中心区域平均颜色: RGB(" + avgR + ", " + avgG + ", " + avgB + ")");
        
        // 判断每个像素是否与中心区域颜色相似
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                int distance = (int) Math.sqrt(
                    Math.pow(r - avgR, 2) + 
                    Math.pow(g - avgG, 2) + 
                    Math.pow(b - avgB, 2)
                );
                
                isSubject[x][y] = distance <= 100; // 与中心区域颜色相似
            }
        }
        
        return isSubject;
    }
    
    /**
     * 形态学处理优化掩码（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage morphologicalProcessing(BufferedImage mask) {
        System.out.println("执行形态学处理...");
        
        int width = mask.getWidth();
        int height = mask.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 复制原图
        Graphics2D g2d = result.createGraphics();
        g2d.drawImage(mask, 0, 0, null);
        g2d.dispose();
        
        // 膨胀操作 - 填充小洞
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int currentAlpha = (mask.getRGB(x, y) >> 24) & 0xFF;
                
                if (currentAlpha == 0) { // 透明像素
                    // 检查周围是否有不透明像素
                    int opaqueNeighbors = 0;
                    for (int dx = -1; dx <= 1; dx++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            if (dx == 0 && dy == 0) continue;
                            int neighborAlpha = (mask.getRGB(x + dx, y + dy) >> 24) & 0xFF;
                            if (neighborAlpha > 0) {
                                opaqueNeighbors++;
                            }
                        }
                    }
                    
                    // 如果周围有足够的不透明像素，填充这个洞
                    if (opaqueNeighbors >= 6) {
                        result.setRGB(x, y, 0xFFFFFFFF);
                    }
                }
            }
        }
        
        // 腐蚀操作 - 去除噪声
        BufferedImage temp = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d2 = temp.createGraphics();
        g2d2.drawImage(result, 0, 0, null);
        g2d2.dispose();
        
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int currentAlpha = (result.getRGB(x, y) >> 24) & 0xFF;
                
                if (currentAlpha > 0) { // 不透明像素
                    // 检查周围是否有透明像素
                    int transparentNeighbors = 0;
                    for (int dx = -1; dx <= 1; dx++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            if (dx == 0 && dy == 0) continue;
                            int neighborAlpha = (result.getRGB(x + dx, y + dy) >> 24) & 0xFF;
                            if (neighborAlpha == 0) {
                                transparentNeighbors++;
                            }
                        }
                    }
                    
                    // 如果周围有太多的透明像素，可能是噪声
                    if (transparentNeighbors >= 6) {
                        temp.setRGB(x, y, 0x00000000);
                    }
                }
            }
        }
        
        System.out.println("形态学处理完成");
        return temp;
    }
    
    /**
     * 使用掩码精确抠图（旧方法）
     * 确保真正的透明背景
     */
    @SuppressWarnings("unused")
    private static BufferedImage extractSubjectWithMask(BufferedImage image, BufferedImage mask) {
        System.out.println("执行精确抠图...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        int subjectPixels = 0;
        int transparentPixels = 0;
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int originalRgb = image.getRGB(x, y);
                int maskRgb = mask.getRGB(x, y);
                
                // 检查掩码是否为白色（主体）
                boolean isSubject = (maskRgb & 0x00FFFFFF) == 0x00FFFFFF;
                
                if (isSubject) {
                    // 保持原色，完全不透明
                    result.setRGB(x, y, originalRgb);
                    subjectPixels++;
                } else {
                    // 设为完全透明 - 这是关键！
                    result.setRGB(x, y, 0x00000000);
                    transparentPixels++;
                }
            }
        }
        
        System.out.println("精确抠图完成: 主体像素=" + subjectPixels + ", 透明像素=" + transparentPixels);
        return result;
    }
    
    /**
     * 验证透明背景
     * 确保图像是真正的RGBA四通道透明图像
     */
    private static void verifyTransparentBackground(BufferedImage image) {
        System.out.println("验证RGBA四通道透明背景...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        
        int transparentPixels = 0;
        int opaquePixels = 0;
        int whitePixels = 0;
        int semiTransparentPixels = 0;
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int alpha = (rgb >> 24) & 0xFF;
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                if (alpha == 0) {
                    transparentPixels++;
                } else if (alpha == 255) {
                    opaquePixels++;
                    // 检查是否为白色像素
                    if (r > 240 && g > 240 && b > 240) {
                        whitePixels++;
                    }
                } else {
                    semiTransparentPixels++;
                }
            }
        }
        
        System.out.println("RGBA四通道透明背景验证结果:");
        System.out.println("- 完全透明像素 (Alpha=0): " + transparentPixels);
        System.out.println("- 完全不透明像素 (Alpha=255): " + opaquePixels);
        System.out.println("- 半透明像素 (0<Alpha<255): " + semiTransparentPixels);
        System.out.println("- 白色像素: " + whitePixels);
        
        // 验证RGBA四通道
        if (transparentPixels > 0) {
            System.out.println("✓ 成功创建透明背景！");
        } else {
            System.out.println("✗ 错误：没有透明像素，背景不是透明的！");
        }
        
        if (opaquePixels > 0) {
            System.out.println("✓ 主体像素保持不透明！");
        } else {
            System.out.println("✗ 错误：没有不透明像素，主体可能丢失！");
        }
        
        if (whitePixels > opaquePixels * 0.1) {
            System.out.println("⚠ 警告：白色像素过多，可能存在白色光晕问题！");
        }
        
        // 验证图像格式
        if (image.getType() == BufferedImage.TYPE_INT_ARGB) {
            System.out.println("✓ 图像格式正确：RGBA四通道 (TYPE_INT_ARGB)");
        } else {
            System.out.println("✗ 错误：图像格式不正确，不是RGBA四通道！");
        }
        
        // 计算透明度比例
        double transparencyRatio = (double) transparentPixels / (width * height);
        System.out.println("✓ 透明度比例: " + String.format("%.2f", transparencyRatio * 100) + "%");
        
        if (transparencyRatio > 0.3) {
            System.out.println("✓ 透明度比例合理，背景已成功透明化！");
        } else {
            System.out.println("⚠ 警告：透明度比例较低，背景可能没有完全透明化！");
        }
    }
    
    /**
     * 应用羽化效果（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage applyFeathering(BufferedImage image) {
        System.out.println("应用羽化效果...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 复制原图
        Graphics2D g2d = result.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        
        // 羽化处理
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int currentAlpha = (image.getRGB(x, y) >> 24) & 0xFF;
                
                if (currentAlpha > 0) {
                    // 检查周围像素
                    int transparentNeighbors = 0;
                    for (int dx = -1; dx <= 1; dx++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            if (dx == 0 && dy == 0) continue;
                            int neighborAlpha = (image.getRGB(x + dx, y + dy) >> 24) & 0xFF;
                            if (neighborAlpha == 0) {
                                transparentNeighbors++;
                            }
                        }
                    }
                    
                    // 如果有透明邻居，创建羽化效果
                    if (transparentNeighbors > 0) {
                        int originalRgb = image.getRGB(x, y);
                        int r = (originalRgb >> 16) & 0xFF;
                        int g = (originalRgb >> 8) & 0xFF;
                        int b = originalRgb & 0xFF;
                        
                        // 根据透明邻居数量调整透明度
                        float featherFactor = 1.0f - (float) transparentNeighbors / 8.0f;
                        featherFactor = (float) Math.pow(featherFactor, 0.5); // 使用平方根使过渡更自然
                        int newAlpha = Math.round(255 * featherFactor);
                        
                        int newRgb = (newAlpha << 24) | (r << 16) | (g << 8) | b;
                        result.setRGB(x, y, newRgb);
                    }
                }
            }
        }
        
        System.out.println("羽化效果完成");
        return result;
    }
    
    
    /**
     * 边缘平滑处理（旧方法）
     * 使用简单的邻域平均
     */
    @SuppressWarnings("unused")
    private static BufferedImage smoothEdges(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 复制原图
        Graphics2D g2d = result.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        
        // 边缘平滑
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int currentAlpha = (image.getRGB(x, y) >> 24) & 0xFF;
                
                if (currentAlpha > 0) {
                    // 检查周围像素
                    int transparentNeighbors = 0;
                    for (int dx = -1; dx <= 1; dx++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            if (dx == 0 && dy == 0) continue;
                            int neighborAlpha = (image.getRGB(x + dx, y + dy) >> 24) & 0xFF;
                            if (neighborAlpha == 0) {
                                transparentNeighbors++;
                            }
                        }
                    }
                    
                    // 如果有透明邻居，创建渐变效果
                    if (transparentNeighbors > 0) {
                        int originalRgb = image.getRGB(x, y);
                        int r = (originalRgb >> 16) & 0xFF;
                        int g = (originalRgb >> 8) & 0xFF;
                        int b = originalRgb & 0xFF;
                        
                        // 简单的透明度调整
                        int newAlpha = Math.max(64, 255 - transparentNeighbors * 30);
                        
                        int newRgb = (newAlpha << 24) | (r << 16) | (g << 8) | b;
                        result.setRGB(x, y, newRgb);
                    }
                }
            }
        }
        
        return result;
    }
    
    /**
     * 智能主体检测（旧方法）
     * 使用多种方法检测图像中的主体
     */
    @SuppressWarnings("unused")
    private static BufferedImage detectSubject(BufferedImage image) {
        System.out.println("执行智能主体检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage mask = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 方法1: 基于颜色聚类的背景检测
        System.out.println("方法1: 基于颜色聚类的背景检测...");
        boolean[][] isBackground = detectBackgroundByClustering(image);
        
        // 方法2: 基于边缘的主体检测
        System.out.println("方法2: 基于边缘的主体检测...");
        boolean[][] isSubjectByEdge = detectSubjectByEdges(image);
        
        // 方法3: 基于中心区域的主体检测
        System.out.println("方法3: 基于中心区域的主体检测...");
        boolean[][] isSubjectByCenter = detectSubjectByCenter(image);
        
        // 综合判断
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                boolean isBg = isBackground[x][y];
                boolean isEdge = isSubjectByEdge[x][y];
                boolean isCenter = isSubjectByCenter[x][y];
                
                // 综合判断：更保守的策略
                // 是边缘主体 或 (不是背景 且 是中心主体)
                boolean isSubject = isEdge || (!isBg && isCenter);
                
                if (isSubject) {
                    mask.setRGB(x, y, 0xFFFFFFFF); // 白色表示主体
                } else {
                    mask.setRGB(x, y, 0x00000000); // 透明表示背景
                }
            }
        }
        
        System.out.println("智能主体检测完成");
        return mask;
    }
    
    /**
     * 基于颜色聚类的背景检测
     */
    private static boolean[][] detectBackgroundByClustering(BufferedImage image) {
        System.out.println("执行颜色聚类背景检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        boolean[][] isBackground = new boolean[width][height];
        
        // 分析边缘像素作为背景样本
        java.util.List<int[]> backgroundSamples = new java.util.ArrayList<>();
        
        // 收集边缘像素作为背景样本
        for (int x = 0; x < width; x++) {
            // 上边缘
            int rgb = image.getRGB(x, 0);
            backgroundSamples.add(new int[]{(rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF});
            
            // 下边缘
            rgb = image.getRGB(x, height - 1);
            backgroundSamples.add(new int[]{(rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF});
        }
        
        for (int y = 0; y < height; y++) {
            // 左边缘
            int rgb = image.getRGB(0, y);
            backgroundSamples.add(new int[]{(rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF});
            
            // 右边缘
            rgb = image.getRGB(width - 1, y);
            backgroundSamples.add(new int[]{(rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF});
        }
        
        // 计算背景色平均值
        int avgR = 0, avgG = 0, avgB = 0;
        for (int[] sample : backgroundSamples) {
            avgR += sample[0];
            avgG += sample[1];
            avgB += sample[2];
        }
        avgR /= backgroundSamples.size();
        avgG /= backgroundSamples.size();
        avgB /= backgroundSamples.size();
        
        System.out.println("检测到背景色: RGB(" + avgR + ", " + avgG + ", " + avgB + ")");
        
        // 计算背景色的标准差
        int variance = 0;
        for (int[] sample : backgroundSamples) {
            int distance = (int) Math.sqrt(
                Math.pow(sample[0] - avgR, 2) + 
                Math.pow(sample[1] - avgG, 2) + 
                Math.pow(sample[2] - avgB, 2)
            );
            variance += distance;
        }
        int threshold = Math.max(50, variance / backgroundSamples.size() + 30);
        
        System.out.println("背景检测阈值: " + threshold);
        
        // 判断每个像素是否为背景
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                int distance = (int) Math.sqrt(
                    Math.pow(r - avgR, 2) + 
                    Math.pow(g - avgG, 2) + 
                    Math.pow(b - avgB, 2)
                );
                
                isBackground[x][y] = distance <= threshold;
            }
        }
        
        return isBackground;
    }
    
    /**
     * 基于边缘的主体检测
     */
    private static boolean[][] detectSubjectByEdges(BufferedImage image) {
        System.out.println("执行边缘主体检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        boolean[][] isSubject = new boolean[width][height];
        
        // 使用Sobel算子检测边缘
        int[][] sobelX = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
        int[][] sobelY = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
        
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int gx = 0, gy = 0;
                for (int i = -1; i <= 1; i++) {
                    for (int j = -1; j <= 1; j++) {
                        int rgb = image.getRGB(x + i, y + j);
                        int gray = (int)(0.299 * ((rgb >> 16) & 0xFF) + 
                                        0.587 * ((rgb >> 8) & 0xFF) + 
                                        0.114 * (rgb & 0xFF));
                        gx += gray * sobelX[i + 1][j + 1];
                        gy += gray * sobelY[i + 1][j + 1];
                    }
                }
                
                int magnitude = (int) Math.sqrt(gx * gx + gy * gy);
                isSubject[x][y] = magnitude > 50; // 提高边缘阈值
            }
        }
        
        return isSubject;
    }
    
    /**
     * 基于中心区域的主体检测
     */
    private static boolean[][] detectSubjectByCenter(BufferedImage image) {
        System.out.println("执行中心区域主体检测...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        boolean[][] isSubject = new boolean[width][height];
        
        // 分析中心区域的颜色分布
        int centerX = width / 2;
        int centerY = height / 2;
        int radius = Math.min(width, height) / 4;
        
        // 收集中心区域的颜色样本
        java.util.List<int[]> centerSamples = new java.util.ArrayList<>();
        for (int x = centerX - radius; x < centerX + radius; x++) {
            for (int y = centerY - radius; y < centerY + radius; y++) {
                if (x >= 0 && x < width && y >= 0 && y < height) {
                    int rgb = image.getRGB(x, y);
                    centerSamples.add(new int[]{(rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF});
                }
            }
        }
        
        // 计算中心区域的平均颜色
        int avgR = 0, avgG = 0, avgB = 0;
        for (int[] sample : centerSamples) {
            avgR += sample[0];
            avgG += sample[1];
            avgB += sample[2];
        }
        avgR /= centerSamples.size();
        avgG /= centerSamples.size();
        avgB /= centerSamples.size();
        
        // 判断每个像素是否与中心区域颜色相似
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                
                int distance = (int) Math.sqrt(
                    Math.pow(r - avgR, 2) + 
                    Math.pow(g - avgG, 2) + 
                    Math.pow(b - avgB, 2)
                );
                
                isSubject[x][y] = distance <= 80; // 提高颜色相似度阈值
            }
        }
        
        return isSubject;
    }
    
    /**
     * 精确抠图（旧方法）
     * 根据主体掩码提取主体
     */
    @SuppressWarnings("unused")
    private static BufferedImage extractSubject(BufferedImage image, BufferedImage mask) {
        System.out.println("执行精确抠图...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int originalRgb = image.getRGB(x, y);
                int maskRgb = mask.getRGB(x, y);
                
                // 检查掩码是否为白色（主体）
                boolean isSubject = (maskRgb & 0x00FFFFFF) == 0x00FFFFFF;
                
                if (isSubject) {
                    // 保持原色，完全不透明
                    result.setRGB(x, y, originalRgb);
                } else {
                    // 设为透明
                    result.setRGB(x, y, 0x00000000);
                }
            }
        }
        
        System.out.println("精确抠图完成");
        return result;
    }
    
    /**
     * 边缘优化（旧方法）
     * 优化抠图边缘的质量
     */
    @SuppressWarnings("unused")
    private static BufferedImage optimizeEdges(BufferedImage image) {
        System.out.println("执行边缘优化...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 复制原图
        Graphics2D g2d = result.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        
        // 边缘羽化处理
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int currentAlpha = (image.getRGB(x, y) >> 24) & 0xFF;
                
                if (currentAlpha > 0) {
                    // 检查周围像素的透明度
                    int transparentNeighbors = 0;
                    int totalNeighbors = 0;
                    
                    for (int dx = -1; dx <= 1; dx++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            if (dx == 0 && dy == 0) continue;
                            totalNeighbors++;
                            
                            int neighborAlpha = (image.getRGB(x + dx, y + dy) >> 24) & 0xFF;
                            if (neighborAlpha == 0) {
                                transparentNeighbors++;
                            }
                        }
                    }
                    
                    // 如果周围有透明像素，创建羽化效果
                    if (transparentNeighbors > 0) {
                        int originalRgb = image.getRGB(x, y);
                        int r = (originalRgb >> 16) & 0xFF;
                        int g = (originalRgb >> 8) & 0xFF;
                        int b = originalRgb & 0xFF;
                        
                        // 根据透明邻居数量调整透明度，使用更平滑的过渡
                        float featherFactor = 1.0f - (float) transparentNeighbors / totalNeighbors;
                        featherFactor = (float) Math.pow(featherFactor, 0.7); // 使用幂函数使过渡更平滑
                        int newAlpha = Math.round(255 * featherFactor);
                        
                        int newRgb = (newAlpha << 24) | (r << 16) | (g << 8) | b;
                        result.setRGB(x, y, newRgb);
                    }
                }
            }
        }
        
        System.out.println("边缘优化完成");
        return result;
    }
    
    /**
     * 最终透明化处理（旧方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage applyFinalTransparency(BufferedImage image) {
        System.out.println("执行最终透明化处理...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 应用高斯模糊进行最终平滑
        float[][] kernel = {
            {0.077f, 0.123f, 0.077f},
            {0.123f, 0.200f, 0.123f},
            {0.077f, 0.123f, 0.077f}
        };
        
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                float rSum = 0, gSum = 0, bSum = 0, aSum = 0;
                
                for (int dx = -1; dx <= 1; dx++) {
                    for (int dy = -1; dy <= 1; dy++) {
                        int rgb = image.getRGB(x + dx, y + dy);
                        float weight = kernel[dx + 1][dy + 1];
                        
                        rSum += ((rgb >> 16) & 0xFF) * weight;
                        gSum += ((rgb >> 8) & 0xFF) * weight;
                        bSum += (rgb & 0xFF) * weight;
                        aSum += ((rgb >> 24) & 0xFF) * weight;
                    }
                }
                
                int r = Math.max(0, Math.min(255, Math.round(rSum)));
                int g = Math.max(0, Math.min(255, Math.round(gSum)));
                int b = Math.max(0, Math.min(255, Math.round(bSum)));
                int a = Math.max(0, Math.min(255, Math.round(aSum)));
                
                int newRgb = (a << 24) | (r << 16) | (g << 8) | b;
                result.setRGB(x, y, newRgb);
            }
        }
        
        System.out.println("最终透明化处理完成");
        return result;
    }
    
    /**
     * 边缘检测和主体分离（旧方法）
     * 使用Sobel算子进行边缘检测
     */
    @SuppressWarnings("unused")
    private static BufferedImage detectEdgesAndSeparate(BufferedImage image) {
        System.out.println("执行边缘检测和主体分离...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // Sobel算子
        int[][] sobelX = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
        int[][] sobelY = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
        
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                // 计算Sobel梯度
                int gx = 0, gy = 0;
                for (int i = -1; i <= 1; i++) {
                    for (int j = -1; j <= 1; j++) {
                        int rgb = image.getRGB(x + i, y + j);
                        int gray = (int)(0.299 * ((rgb >> 16) & 0xFF) + 
                                        0.587 * ((rgb >> 8) & 0xFF) + 
                                        0.114 * (rgb & 0xFF));
                        gx += gray * sobelX[i + 1][j + 1];
                        gy += gray * sobelY[i + 1][j + 1];
                    }
                }
                
                int magnitude = (int) Math.sqrt(gx * gx + gy * gy);
                
                // 根据边缘强度决定透明度
                int alpha = 255;
                if (magnitude > 50) { // 强边缘，保持不透明
                    alpha = 255;
                } else if (magnitude > 20) { // 中等边缘，部分透明
                    alpha = 128 + (magnitude - 20) * 4;
                } else { // 弱边缘或背景，设为透明
                    alpha = 0;
                }
                
                // 保持原色但应用新的透明度
                int originalRgb = image.getRGB(x, y);
                int r = (originalRgb >> 16) & 0xFF;
                int g = (originalRgb >> 8) & 0xFF;
                int b = originalRgb & 0xFF;
                
                int newRgb = (alpha << 24) | (r << 16) | (g << 8) | b;
                result.setRGB(x, y, newRgb);
            }
        }
        
        System.out.println("边缘检测完成");
        return result;
    }
    
    
    /**
     * 高级抗锯齿处理（旧方法）
     * 使用高斯模糊和边缘平滑
     */
    @SuppressWarnings("unused")
    private static BufferedImage applyAdvancedAntiAliasing(BufferedImage image) {
        System.out.println("应用高级抗锯齿处理...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 高斯模糊核
        float[][] kernel = {
            {0.077f, 0.123f, 0.077f},
            {0.123f, 0.200f, 0.123f},
            {0.077f, 0.123f, 0.077f}
        };
        
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                float rSum = 0, gSum = 0, bSum = 0, aSum = 0;
                
                // 应用高斯模糊
                for (int dx = -1; dx <= 1; dx++) {
                    for (int dy = -1; dy <= 1; dy++) {
                        int rgb = image.getRGB(x + dx, y + dy);
                        float weight = kernel[dx + 1][dy + 1];
                        
                        rSum += ((rgb >> 16) & 0xFF) * weight;
                        gSum += ((rgb >> 8) & 0xFF) * weight;
                        bSum += (rgb & 0xFF) * weight;
                        aSum += ((rgb >> 24) & 0xFF) * weight;
                    }
                }
                
                int r = Math.round(rSum);
                int g = Math.round(gSum);
                int b = Math.round(bSum);
                int a = Math.round(aSum);
                
                // 确保值在有效范围内
                r = Math.max(0, Math.min(255, r));
                g = Math.max(0, Math.min(255, g));
                b = Math.max(0, Math.min(255, b));
                a = Math.max(0, Math.min(255, a));
                
                int newRgb = (a << 24) | (r << 16) | (g << 8) | b;
                result.setRGB(x, y, newRgb);
            }
        }
        
        System.out.println("抗锯齿处理完成");
        return result;
    }
    
    /**
     * 最终优化处理（旧方法）
     * 清理残留和优化边缘
     */
    @SuppressWarnings("unused")
    private static BufferedImage finalOptimization(BufferedImage image) {
        System.out.println("执行最终优化处理...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 复制原图
        Graphics2D g2d = result.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        
        // 清理孤立的透明像素
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int currentAlpha = (image.getRGB(x, y) >> 24) & 0xFF;
                
                if (currentAlpha == 0) {
                    // 检查周围是否有不透明像素
                    int opaqueNeighbors = 0;
                    for (int dx = -1; dx <= 1; dx++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            if (dx == 0 && dy == 0) continue;
                            int neighborAlpha = (image.getRGB(x + dx, y + dy) >> 24) & 0xFF;
                            if (neighborAlpha > 128) {
                                opaqueNeighbors++;
                            }
                        }
                    }
                    
                    // 如果周围有很多不透明像素，创建渐变
                    if (opaqueNeighbors >= 4) {
                        int originalRgb = image.getRGB(x, y);
                        int r = (originalRgb >> 16) & 0xFF;
                        int g = (originalRgb >> 8) & 0xFF;
                        int b = originalRgb & 0xFF;
                        int newAlpha = 64; // 半透明
                        
                        int newRgb = (newAlpha << 24) | (r << 16) | (g << 8) | b;
                        result.setRGB(x, y, newRgb);
                    }
                }
            }
        }
        
        System.out.println("最终优化完成");
        return result;
    }
    
    /**
     * 高级白色背景移除算法（备用方法）
     * 结合多种检测方法
     */
    @SuppressWarnings("unused")
    private static BufferedImage removeWhiteBackgroundAdvanced(BufferedImage image) {
        System.out.println("使用高级白色背景移除算法...");
        
        // 创建新的透明图像
        BufferedImage transparentImage = new BufferedImage(
            image.getWidth(), 
            image.getHeight(), 
            BufferedImage.TYPE_INT_ARGB
        );
        
        // 获取图像尺寸
        int width = image.getWidth();
        int height = image.getHeight();
        
        // 背景检测参数
        int whiteThreshold = 240; // 白色阈值，低于此值认为是白色
        int tolerance = 15; // 容差值
        
        System.out.println("使用参数: 白色阈值=" + whiteThreshold + ", 容差=" + tolerance);
        
        // 统计处理信息
        int totalPixels = width * height;
        int transparentPixels = 0;
        int keptPixels = 0;
        
        // 处理每个像素
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                
                // 提取RGB值
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                int a = (rgb >> 24) & 0xFF;
                
                // 检查是否为背景色（多种检测方法）
                boolean isBackground = isBackgroundColor(r, g, b, whiteThreshold, tolerance);
                
                if (isBackground) {
                    // 设置为透明
                    transparentImage.setRGB(x, y, 0x00000000); // 完全透明
                    transparentPixels++;
                } else {
                    // 保持原像素，但确保Alpha通道正确
                    int newRgb = (a << 24) | (r << 16) | (g << 8) | b;
                    transparentImage.setRGB(x, y, newRgb);
                    keptPixels++;
                }
            }
        }
        
        System.out.println("高级背景移除完成: 总像素=" + totalPixels + 
                          ", 透明像素=" + transparentPixels + 
                          ", 保留像素=" + keptPixels);
        
        return transparentImage;
    }
    
    /**
     * 检测是否为背景色
     * 使用多种方法提高检测准确性
     */
    private static boolean isBackgroundColor(int r, int g, int b, int threshold, int tolerance) {
        // 方法1: 检查是否为纯白色或接近白色
        if (r >= threshold && g >= threshold && b >= threshold) {
            return true;
        }
        
        // 方法2: 检查RGB值是否接近（灰色系）
        int maxDiff = Math.max(Math.abs(r - g), Math.max(Math.abs(r - b), Math.abs(g - b)));
        if (maxDiff <= tolerance && r >= threshold - tolerance) {
            return true;
        }
        
        // 方法3: 检查亮度是否足够高
        double brightness = 0.299 * r + 0.587 * g + 0.114 * b;
        if (brightness >= threshold) {
            return true;
        }
        
        // 方法4: 检查HSV中的V值（明度）
        float[] hsv = rgbToHsv(r, g, b);
        if (hsv[2] >= threshold / 255.0f) { // V值归一化
            return true;
        }
        
        return false;
    }
    
    /**
     * RGB转HSV
     */
    private static float[] rgbToHsv(int r, int g, int b) {
        float[] hsv = new float[3];
        float rf = r / 255.0f;
        float gf = g / 255.0f;
        float bf = b / 255.0f;
        
        float max = Math.max(rf, Math.max(gf, bf));
        float min = Math.min(rf, Math.min(gf, bf));
        float delta = max - min;
        
        // V (Value/Brightness)
        hsv[2] = max;
        
        // S (Saturation)
        hsv[1] = max == 0 ? 0 : delta / max;
        
        // H (Hue)
        if (delta == 0) {
            hsv[0] = 0;
        } else if (max == rf) {
            hsv[0] = 60 * ((gf - bf) / delta);
        } else if (max == gf) {
            hsv[0] = 60 * (2 + (bf - rf) / delta);
        } else {
            hsv[0] = 60 * (4 + (rf - gf) / delta);
        }
        
        if (hsv[0] < 0) hsv[0] += 360;
        
        return hsv;
    }
    
    /**
     * 应用边缘平滑处理（备用方法）
     * 减少锯齿效果，使边缘更自然
     */
    @SuppressWarnings("unused")
    private static BufferedImage applyEdgeSmoothing(BufferedImage image) {
        System.out.println("应用边缘平滑处理...");
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage smoothedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        // 复制原图
        Graphics2D g2d = smoothedImage.createGraphics();
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        
        // 边缘平滑处理
        for (int x = 1; x < width - 1; x++) {
            for (int y = 1; y < height - 1; y++) {
                int currentAlpha = (image.getRGB(x, y) >> 24) & 0xFF;
                
                // 如果当前像素是透明的，检查周围像素
                if (currentAlpha == 0) {
                    int opaqueNeighbors = 0;
                    int totalAlpha = 0;
                    
                    // 检查8个邻居像素
                    for (int dx = -1; dx <= 1; dx++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            if (dx == 0 && dy == 0) continue;
                            
                            int neighborAlpha = (image.getRGB(x + dx, y + dy) >> 24) & 0xFF;
                            if (neighborAlpha > 0) {
                                opaqueNeighbors++;
                                totalAlpha += neighborAlpha;
                            }
                        }
                    }
                    
                    // 如果周围有不透明像素，创建渐变效果
                    if (opaqueNeighbors > 0) {
                        int avgAlpha = totalAlpha / opaqueNeighbors;
                        int newAlpha = Math.min(avgAlpha / 3, 128); // 限制透明度
                        
                        if (newAlpha > 0) {
                            int originalRgb = image.getRGB(x, y);
                            int r = (originalRgb >> 16) & 0xFF;
                            int g = (originalRgb >> 8) & 0xFF;
                            int b = originalRgb & 0xFF;
                            
                            int newRgb = (newAlpha << 24) | (r << 16) | (g << 8) | b;
                            smoothedImage.setRGB(x, y, newRgb);
                        }
                    }
                }
            }
        }
        
        System.out.println("边缘平滑处理完成");
        return smoothedImage;
    }
    
    
    /**
     * 基于检测到的背景色进行背景移除（备用方法）
     */
    @SuppressWarnings("unused")
    private static BufferedImage removeBackgroundByColor(BufferedImage image, int[] backgroundColor, int tolerance) {
        System.out.println("基于检测背景色进行移除，容差: " + tolerance);
        
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        int bgR = backgroundColor[0];
        int bgG = backgroundColor[1];
        int bgB = backgroundColor[2];
        
        int transparentPixels = 0;
        int keptPixels = 0;
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;
                int a = (rgb >> 24) & 0xFF;
                
                // 计算与背景色的距离
                int distance = (int) Math.sqrt(
                    Math.pow(r - bgR, 2) + 
                    Math.pow(g - bgG, 2) + 
                    Math.pow(b - bgB, 2)
                );
                
                if (distance <= tolerance) {
                    // 设置为透明
                    result.setRGB(x, y, 0x00000000);
                    transparentPixels++;
                } else {
                    // 保持原像素
                    int newRgb = (a << 24) | (r << 16) | (g << 8) | b;
                    result.setRGB(x, y, newRgb);
                    keptPixels++;
                }
            }
        }
        
        System.out.println("背景移除结果: 透明像素=" + transparentPixels + ", 保留像素=" + keptPixels);
        return result;
    }
    
    private static byte[] convertToByteArray(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return baos.toByteArray();
    }
    
    /**
     * 上传文件到MinIO
     * 
     * @param imageBytes 图片字节数组
     * @return 上传后的文件名
     * @throws Exception 上传异常
     */
    private static String uploadToMinIO(byte[] imageBytes) throws Exception {
        try {
            // 创建MinIO客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(MINIO_ENDPOINT)
                    .credentials(MINIO_ACCESS_KEY, MINIO_SECRET_KEY)
                    .build();
            
            // 生成唯一文件名
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String uuid = UUID.randomUUID().toString().substring(0, 8);
            String fileName = "transparent_" + timestamp + "_" + uuid + ".png";
            
            // 确保存储桶存在
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET_NAME).build());
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKET_NAME).build());
                System.out.println("创建存储桶: " + BUCKET_NAME);
            }
            
            // 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(BUCKET_NAME)
                            .object(fileName)
                            .stream(new ByteArrayInputStream(imageBytes), imageBytes.length, -1)
                            .contentType("image/png")
                            .build()
            );
            
            System.out.println("文件上传成功: " + BUCKET_NAME + "/" + fileName);
            return fileName;
            
        } catch (Exception e) {
            System.err.println("上传到MinIO失败: " + e.getMessage());
            throw new Exception("上传到MinIO失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 生成临时访问链接
     * 
     * @param fileName 文件名
     * @return 临时访问链接
     */
    private static String generateTempUrl(String fileName) {
        try {
            // 创建MinIO客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(MINIO_ENDPOINT)
                    .credentials(MINIO_ACCESS_KEY, MINIO_SECRET_KEY)
                    .build();
            
            // 生成7天有效期的预签名URL
            String presignedUrl = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(BUCKET_NAME)
                            .object(fileName)
                            .expiry(7, TimeUnit.DAYS) // 7天有效期
                            .build()
            );
            
            System.out.println("生成临时链接成功，有效期: 7天");
            return presignedUrl;
            
        } catch (Exception e) {
            System.err.println("生成临时链接失败: " + e.getMessage());
            return null;
        }
    }
}