使用百度完成gui的图像处理(需要下载百度的javasdk文档,主要工具带代码在sdk之中,以下代码为如何利用代码实现图像增强和特效处理)

package Gui;

import com.baidu.aip.imageprocess.AipImageProcess;
import org.json.JSONObject;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;

public class ImageUploader extends JFrame {
    public static final String APP_ID = "44423840";
    public static final String API_KEY = "fcNbi6SVub4kQN7cuW4YITb1";
    public static final String SECRET_KEY = "ncTXhqWo0z8EbO5fHr3XxUKZ59lajaMh";
    public static String imagepath = "";
    public static JLabel rightLabel = new JLabel(new ImageIcon(""));
    public ImageUploader() {
        setTitle("图像特效和图像增强");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 初始化图片面板
        JPanel imagePanel = new JPanel();
        JLabel imageLabel = new JLabel(new ImageIcon(""));  // 用实际的默认图片路径替换 "default_image.jpg"
        imagePanel.add(imageLabel);

        JPanel rightPanel = new JPanel();
        rightPanel.setPreferredSize(new Dimension(400, 500));
          // 用实际的图片路径替换 "right_image.jpg"
        rightPanel.add(rightLabel);



        // 初始化上传按钮
        JButton uploadButton = new JButton("点击上传");
        JButton TranButton = new JButton("人物动漫化");
        JButton contrastEnhance = new JButton("图像对比度增强");
        JButton colourize = new JButton("黑白图像上色");
        /**
         * @uploadButton:上传图片
         * @TranButton:将图片动漫化
         * @colourize:黑白图片上色
         * @contrastEnhance:图像对比度增强
         *
         */
        uploadButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                int result = fileChooser.showOpenDialog(ImageUploader.this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    try {
                        BufferedImage uploadedImage = ImageIO.read(selectedFile);
                        imageLabel.setIcon(new ImageIcon(uploadedImage));
                        imagepath=selectedFile.getAbsolutePath();


                    } catch (IOException ex) {
                        System.out.println("Error reading image: " + ex.getMessage());
                    }
                }
            }
        });
        TranButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SelfieAnime(imagepath);
                showDealedPicture();
            }
        });
        colourize.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Colourize(imagepath);
                showDealedPicture();

            }
        });

        /**
         * 设置按钮的相对位置
         */
        setLayout(new GridBagLayout());
        contrastEnhance.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                    ContrastEnhance(imagepath);
                showDealedPicture();
            }
        });

        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;

        constraints.gridx = 0;
        constraints.gridy = 0;
        add(imagePanel, constraints);

        constraints.gridy = 1;
        add(uploadButton, constraints);
        constraints.gridy = 2;
        add(TranButton, constraints);
        constraints.gridy = 3;
        add(colourize, constraints);
        constraints.gridy = 4;
        add(contrastEnhance, constraints);

        constraints.gridx=1;
        constraints.gridy = 0;
        add(rightLabel, constraints);

        setVisible(true);
    }

    public static String getImagepath() {
        return imagepath;
    }

    public static void setImagepath(String imagepath) {
        ImageUploader.imagepath = imagepath;
    }

    public  static  void Colourize(String imagepath){
        AipImageProcess client = new AipImageProcess(APP_ID, API_KEY, SECRET_KEY);

        // 可选:设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选:设置代理服务器地址, http和socket二选一,或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 调用接口

        JSONObject res = client.colourize(imagepath, new HashMap<String, String>());


        JSONObject jsonObject = new JSONObject(res.toString(2));
        String base64Image = jsonObject.getString("image");
        String filePath = "C:\\Users\\86158\\Pictures\\1\\image.txt";
        System.out.println("Base64 image: " + base64Image);
        writeBase64ToFile(base64Image,filePath);
        getImage();
    }
    public  static  void SelfieAnime(String filepath){
        AipImageProcess client = new AipImageProcess(APP_ID, API_KEY, SECRET_KEY);

        // 可选:设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选:设置代理服务器地址, http和socket二选一,或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 调用接口

        JSONObject res = client.selfieAnime(filepath, new HashMap<String, String>());


        JSONObject jsonObject = new JSONObject(res.toString(2));
        String base64Image = jsonObject.getString("image");
        String filePath = "C:\\Users\\86158\\Pictures\\1\\image.txt";
        System.out.println("Base64 image: " + base64Image);
        writeBase64ToFile(base64Image,filePath);
        getImage();
    }
    public  static  void ContrastEnhance(String filepath){
        AipImageProcess client = new AipImageProcess(APP_ID, API_KEY, SECRET_KEY);

        // 可选:设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选:设置代理服务器地址, http和socket二选一,或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 调用接口

        JSONObject res = client.contrastEnhance(filepath, new HashMap<String, String>());


        JSONObject jsonObject = new JSONObject(res.toString(2));
        String base64Image = jsonObject.getString("image");
        String filePath = "C:\\Users\\86158\\Pictures\\1\\image.txt";
        System.out.println("Base64 image: " + base64Image);
        writeBase64ToFile(base64Image,filePath);
        getImage();
    }
    public  static void getImage(){
        String filePath = "C:\\Users\\86158\\Pictures\\1\\image.txt"; // 替换为你的文本文件路径
        String base64String = "";
        BufferedImage img = null;

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                base64String += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将Base64编码字符串解码为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64String);
        String outputPath = "C:\\Users\\86158\\Pictures\\1\\15.jpg"; // 替换为你的输出图片路径
        try {
            Files.write(Paths.get(outputPath), imageBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void writeBase64ToFile(String base64Image, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(base64Image);
        } catch (IOException e) {
            System.out.println("Error writing to file: " + e.getMessage());
        }
    }
    public  static  void showDealedPicture(){
        String secondImagePath = "C:\\Users\\86158\\Pictures\\1\\15.jpg";  // 用实际的第二张图片路径替换
        try {
            BufferedImage secondImage = ImageIO.read(new File(secondImagePath));
            EventQueue.invokeLater(() -> rightLabel.setIcon(new ImageIcon(secondImage)));
        } catch (IOException ex) {
            System.out.println("Error reading second image: " + ex.getMessage());
        }

    }
    public static void main(String[] args) {
        new ImageUploader();
    }
}

 

posted @ 2023-12-06 18:15  cojames  阅读(17)  评论(0编辑  收藏  举报