po3a  

 

package api;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class BaiduImageProcess {

    private static final String ACCESS_TOKEN = "24.7416ce38f0a79d20e68a0338d5ebc8de.2592000.1734505386.282335-116286313";

    /**
     * 人像动漫化处理
     * @param imagePath 本地图片文件路径
     * @return 动漫化后的图片Base64编码字符串
     */
    public static String animefyImage(String imagePath) {
        try {
            byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
            String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);
            String encodedImage = URLEncoder.encode(imageBase64, "UTF-8");

            String requestUrl = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=" + ACCESS_TOKEN;
            String params = "image=" + encodedImage;

            HttpURLConnection conn = (HttpURLConnection) new URL(requestUrl).openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setDoOutput(true);

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = params.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                return response.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 提高图片清晰度
     *
     * @param imagePath 本地图片文件路径
     * @return 清晰度提高后的图片Base64编码字符串
     */
    public static String enhanceImageDefinition(String imagePath) {
        try {
            byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
            String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);
            String encodedImage = URLEncoder.encode(imageBase64, "UTF-8");

            String requestUrl = "https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance?access_token=" + ACCESS_TOKEN;
            String params = "image=" + encodedImage;

            HttpURLConnection conn = (HttpURLConnection) new URL(requestUrl).openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setDoOutput(true);

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = params.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                return response.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static BufferedImage base64ToImage(String base64Image) throws IOException {
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
        return ImageIO.read(bis);
    }


}
package GUI;

import api.BaiduImageProcess;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class ImageProcessorGUI extends JFrame {
    private JButton btnChooseImage;
    private JComboBox<String> cmbActions;
    private JLabel lblOriginalImage;
    private JLabel lblProcessedImage;
    private ImageIcon originalImageIcon;

    public ImageProcessorGUI() {
        // 窗口标题和大小
        setTitle("智能图片处理工具");
        setSize(900, 650);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout(10, 10));

        // 主色调配置
        Color primaryColor = new Color(0xA194CC); // 蓝色
        Color secondaryColor = new Color(0xE5E1FA); // 浅蓝背景
        Color buttonColor = new Color(0xE8CC5B); // 金黄色

        // 顶部面板(上传按钮和功能选择)
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        topPanel.setBackground(secondaryColor);
        JLabel title = new JLabel("智能图片处理工具");
        title.setFont(new Font("微软雅黑", Font.BOLD, 20));
        title.setForeground(primaryColor);

        btnChooseImage = new JButton("上传图片");
        btnChooseImage.setPreferredSize(new Dimension(120, 40));
        btnChooseImage.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        btnChooseImage.setBackground(buttonColor);
        btnChooseImage.setForeground(Color.BLACK);

        cmbActions = new JComboBox<>(new String[]{"图像特效", "图片增强"});
        cmbActions.setPreferredSize(new Dimension(150, 30));
        cmbActions.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        cmbActions.setBackground(Color.WHITE);

        topPanel.add(title);
        topPanel.add(btnChooseImage);
        topPanel.add(cmbActions);
        add(topPanel, BorderLayout.NORTH);

        // 图片展示区域
        JPanel imagePanel = new JPanel(new GridLayout(1, 2, 20, 10));
        imagePanel.setBackground(Color.WHITE);

        lblOriginalImage = createImageLabel("上传的图片", primaryColor);
        lblProcessedImage = createImageLabel("处理后的图片", primaryColor);

        imagePanel.add(lblOriginalImage);
        imagePanel.add(lblProcessedImage);
        add(imagePanel, BorderLayout.CENTER);

        // 事件绑定
        btnChooseImage.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            int option = fileChooser.showOpenDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                originalImageIcon = new ImageIcon(selectedFile.getAbsolutePath());
                lblOriginalImage.setIcon(new ImageIcon(originalImageIcon.getImage().getScaledInstance(400, 500, Image.SCALE_SMOOTH)));
                lblOriginalImage.setText(null);
                processImage(selectedFile.getAbsolutePath());
            }
        });
    }

    /**
     * 创建图片显示标签
     */
    private JLabel createImageLabel(String text, Color borderColor) {
        JLabel label = new JLabel(text, SwingConstants.CENTER);
        label.setPreferredSize(new Dimension(400, 500));
        label.setBorder(BorderFactory.createLineBorder(borderColor, 3));
        label.setFont(new Font("微软雅黑", Font.BOLD, 16));
        label.setBackground(Color.WHITE);
        label.setOpaque(true);
        return label;
    }

    /**
     * 处理图片
     */
    private void processImage(String imagePath) {
        String action = (String) cmbActions.getSelectedItem();
        try {
            String response;
            if ("图像特效".equals(action)) {
                response = BaiduImageProcess.animefyImage(imagePath);
            } else if ("图片增强".equals(action)) {
                response = BaiduImageProcess.enhanceImageDefinition(imagePath);
            } else {
                return;
            }
            if (response != null) {
                JSONObject jsonResponse = new JSONObject(response);
                String base64Image = jsonResponse.getString("image");
                BufferedImage processedImage = BaiduImageProcess.base64ToImage(base64Image);
                lblProcessedImage.setIcon(new ImageIcon(processedImage.getScaledInstance(400, 500, Image.SCALE_SMOOTH)));
                lblProcessedImage.setText(null);
            } else {
                JOptionPane.showMessageDialog(this, "处理失败");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "处理失败: " + ex.getMessage());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new ImageProcessorGUI().setVisible(true));
    }
}
posted on 2024-11-20 09:28  po3a  阅读(10)  评论(0)    收藏  举报