首页 > 其他分享 >基于百度API的图像处理实现

基于百度API的图像处理实现

时间:2023-12-26 19:57:38浏览次数:36  
标签:IOException return String API static 图像处理 import new 百度

软件构造的小实验,现给出源码造福未来学弟

依赖

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.1</version> <!-- 请替换为最新版本 -->
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>
 <!-- https://mvnrepository.com/artifact/com.github.insubstantial/substance -->
<dependency>
     <groupId>com.github.insubstantial</groupId>
     <artifactId>substance</artifactId>
     <version>7.3</version>
</dependency>

图像功能

图片清晰度增强
package com.std.www.homework.work2;

import okhttp3.*;
import org.json.JSONObject;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class PictureClear {
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static String getPicture(String path) throws IOException{
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(path,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String res= response.body().string();
        return res;
    }
    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息,不带文件头
     * @throws IOException IO异常
     */
    private static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}
人像动漫化
 package com.std.www.homework.work2;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class PictureAnime {
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static String getPicture(String path) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(path,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String res= response.body().string();
        return res;
    }
    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息,不带文件头
     * @throws IOException IO异常
     */
    private static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}

 

黑白图像上色
package com.std.www.homework.work2;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class PictureColourize {
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static String getPicture(String path) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(path,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-process/v1/colourize?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String res= response.body().string();
        return res;
    }
    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息,不带文件头
     * @throws IOException IO异常
     */
    private static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}
图像色彩增强
 package com.std.www.homework.work2;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class PictureColorEnhance {
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static String getPicture(String path) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(path,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-process/v1/color_enhance?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String res= response.body().string();
        return res;
    }
    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息,不带文件头
     * @throws IOException IO异常
     */
    private static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}
图像对比度增强
package com.std.www.homework.work2;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class PictureContrastEnhance {
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static String getPicture(String path) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(path,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-process/v1/contrast_enhance?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String res= response.body().string();
        return res;
    }
    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息,不带文件头
     * @throws IOException IO异常
     */
    private static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}
图像无损放大
 package com.std.www.homework.work2;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class PictureQualityEnhance {
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static String getPicture(String path) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(path,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-process/v1/image_quality_enhance?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String res= response.body().string();
        return res;
    }
    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息,不带文件头
     * @throws IOException IO异常
     */
    private static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}
图像去雾
package com.std.www.homework.work2;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class PictureDehaze {
    public static final String API_KEY = "";
    public static final String SECRET_KEY = "";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static String getPicture(String path) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image="+getFileContentAsBase64(path,true));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-process/v1/dehaze?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String res= response.body().string();
        return res;
    }
    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息,不带文件头
     * @throws IOException IO异常
     */
    private static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}

功能调用模块

package com.std.www.homework.work2;

import java.io.IOException;

public class Picture {

    public static String pictureClear(String path) throws IOException {
        return PictureClear.getPicture(path);
    }
    public static String pictureAnime(String path) throws IOException {
        return PictureAnime.getPicture(path);
    }
    public static String pictureColourize(String path) throws IOException {
        return PictureColourize.getPicture(path);
    }
    public static String pictureColorEnhance(String path) throws IOException {
        return PictureColorEnhance.getPicture(path);
    }
    public static String pictureContrastEnhance(String path) throws IOException {
        return PictureContrastEnhance.getPicture(path);
    }
    public static String pictureQualityEnhance(String path) throws IOException {
        return PictureQualityEnhance.getPicture(path);
    }
    public static String pictureDehaze(String path) throws IOException {
        return PictureDehaze.getPicture(path);
    }
}

GUI界面模块

package com.std.www.homework.work2;

import org.json.JSONObject;
import org.pushingpixels.substance.api.skin.SubstanceGeminiLookAndFeel;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;

public class PictureGUI {
    private static String imgPath;
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("图像转换器");
        frame.setSize(1200, 900);
        frame.setLayout(null);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Font font = new Font("宋体", Font.BOLD, 25);
        JButton selectButton=new JButton("选中图片");
        selectButton.setFont(font);
        selectButton.setBounds(20,50,250,50);
        JButton jButton1=new JButton("图像清晰度增强");
        jButton1.setFont(font);
        jButton1.setBounds(300,50,250,50);
        JButton jButton2=new JButton("人像动漫化");
        jButton2.setFont(font);
        jButton2.setBounds(580,50,250,50);
        JButton jButton3=new JButton("黑白图像上色");
        jButton3.setFont(font);
        jButton3.setBounds(860,50,250,50);
        JButton jButton4=new JButton("图像色彩增强");
        jButton4.setFont(font);
        jButton4.setBounds(20,150,250,50);
        JButton jButton5=new JButton("图像对比度增强");
        jButton5.setFont(font);
        jButton5.setBounds(300,150,250,50);
        JButton jButton6=new JButton("图像无损放大");
        jButton6.setFont(font);
        jButton6.setBounds(580,150,250,50);
        JButton jButton7=new JButton("图像去雾");
        jButton7.setFont(font);
        jButton7.setBounds(860,150,250,50);

        JPanel sourcePanel = createStyledPanel(100, 300, 400, 400, "原图片");
        JPanel resPanel = createStyledPanel(700, 300, 400, 400, "结果图片");
        selectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setCurrentDirectory(new File("D:\\JavaProject\\JuniorProject\\Project1\\src\\main\\data\\Img"));
                int result = fileChooser.showOpenDialog(null);

                if (result == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    imgPath=selectedFile.getAbsolutePath();
                    displayImage(selectedFile, sourcePanel);
                }
            }
        });
        jButton1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if(imgPath==null){
                        JOptionPane.showMessageDialog(frame, "请选择图片");
                        return;
                    }
                    String res=Picture.pictureClear(imgPath);
                    JSONObject jsonObject = new JSONObject(res);
                    String base64Image =jsonObject.getString("image");
                    byte[] imageBytes = Base64.getDecoder().decode(base64Image);
                    Path outputPath = Paths.get("Project1/src/main/data/Img/清晰度增强后的图片.png");
                    Files.write(outputPath, imageBytes, StandardOpenOption.CREATE);
                    JOptionPane.showMessageDialog(frame, "图像保存成功,文件路径:" + outputPath);
                    displayImage(new File(outputPath.toUri()),resPanel);

                }catch (Exception ep){
                    ep.printStackTrace();
                }
            }
        });
        jButton2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if(imgPath==null){
                        JOptionPane.showMessageDialog(frame, "请选择图片");
                        return;
                    }
                    String res=Picture.pictureAnime(imgPath);
                    JSONObject jsonObject = new JSONObject(res);
                    String base64Image =jsonObject.getString("image");
                    byte[] imageBytes = Base64.getDecoder().decode(base64Image);
                    Path outputPath = Paths.get("Project1/src/main/data/Img/动漫化后的图片.png");
                    Files.write(outputPath, imageBytes, StandardOpenOption.CREATE);
                    JOptionPane.showMessageDialog(frame, "图像保存成功,文件路径:" + outputPath);
                    displayImage(new File(outputPath.toUri()),resPanel);

                }catch (Exception ep){
                    ep.printStackTrace();
                }
            }
        });
        jButton3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if(imgPath==null){
                        JOptionPane.showMessageDialog(frame, "请选择图片");
                        return;
                    }
                    String res=Picture.pictureColourize(imgPath);
                    JSONObject jsonObject = new JSONObject(res);
                    String base64Image =jsonObject.getString("image");
                    byte[] imageBytes = Base64.getDecoder().decode(base64Image);
                    Path outputPath = Paths.get("Project1/src/main/data/Img/上色后的图片.png");
                    Files.write(outputPath, imageBytes, StandardOpenOption.CREATE);
                    JOptionPane.showMessageDialog(frame, "图像保存成功,文件路径:" + outputPath);
                    displayImage(new File(outputPath.toUri()),resPanel);

                }catch (Exception ep){
                    ep.printStackTrace();
                }
            }
        });

        jButton4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if(imgPath==null){
                        JOptionPane.showMessageDialog(frame, "请选择图片");
                        return;
                    }
                    String res=Picture.pictureColorEnhance(imgPath);
                    JSONObject jsonObject = new JSONObject(res);
                    String base64Image =jsonObject.getString("image");
                    byte[] imageBytes = Base64.getDecoder().decode(base64Image);
                    Path outputPath = Paths.get("Project1/src/main/data/Img/色彩增强后的图片.png");
                    Files.write(outputPath, imageBytes, StandardOpenOption.CREATE);
                    JOptionPane.showMessageDialog(frame, "图像保存成功,文件路径:" + outputPath);
                    displayImage(new File(outputPath.toUri()),resPanel);

                }catch (Exception ep){
                    ep.printStackTrace();
                }
            }
        });

        jButton5.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if(imgPath==null){
                        JOptionPane.showMessageDialog(frame, "请选择图片");
                        return;
                    }
                    String res=Picture.pictureContrastEnhance(imgPath);
                    JSONObject jsonObject = new JSONObject(res);
                    String base64Image =jsonObject.getString("image");
                    byte[] imageBytes = Base64.getDecoder().decode(base64Image);
                    Path outputPath = Paths.get("Project1/src/main/data/Img/对比度增强后的图片.png");
                    Files.write(outputPath, imageBytes, StandardOpenOption.CREATE);
                    JOptionPane.showMessageDialog(frame, "图像保存成功,文件路径:" + outputPath);
                    displayImage(new File(outputPath.toUri()),resPanel);

                }catch (Exception ep){
                    ep.printStackTrace();
                }
            }
        });

        jButton6.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if(imgPath==null){
                        JOptionPane.showMessageDialog(frame, "请选择图片");
                        return;
                    }
                    String res=Picture.pictureQualityEnhance(imgPath);
                    JSONObject jsonObject = new JSONObject(res);
                    String base64Image =jsonObject.getString("image");
                    byte[] imageBytes = Base64.getDecoder().decode(base64Image);
                    Path outputPath = Paths.get("Project1/src/main/data/Img/放大后的图片.png");
                    Files.write(outputPath, imageBytes, StandardOpenOption.CREATE);
                    JOptionPane.showMessageDialog(frame, "图像保存成功,文件路径:" + outputPath);
                    displayImage(new File(outputPath.toUri()),resPanel);

                }catch (Exception ep){
                    ep.printStackTrace();
                }
            }
        });

        jButton7.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if(imgPath==null){
                        JOptionPane.showMessageDialog(frame, "请选择图片");
                        return;
                    }
                    String res=Picture.pictureDehaze(imgPath);
                    JSONObject jsonObject = new JSONObject(res);
                    String base64Image =jsonObject.getString("image");
                    byte[] imageBytes = Base64.getDecoder().decode(base64Image);
                    Path outputPath = Paths.get("Project1/src/main/data/Img/去雾后的图片.png");
                    Files.write(outputPath, imageBytes, StandardOpenOption.CREATE);
                    JOptionPane.showMessageDialog(frame, "图像保存成功,文件路径:" + outputPath);
                    displayImage(new File(outputPath.toUri()),resPanel);

                }catch (Exception ep){
                    ep.printStackTrace();
                }
            }
        });



        frame.add(selectButton);
        frame.add(jButton1);
        frame.add(jButton2);
        frame.add(jButton3);
        frame.add(jButton4);
        frame.add(jButton5);
        frame.add(jButton6);
        frame.add(jButton7);
        frame.add(sourcePanel);
        frame.add(resPanel);
        frame.setVisible(true);

    }

    private static JPanel createStyledPanel(int x, int y, int width, int height, String title) {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBounds(x, y, width, height);
        panel.setBorder(new LineBorder(Color.BLUE));
        panel.setBackground(Color.LIGHT_GRAY);

        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("宋体", Font.BOLD, 20));
        titleLabel.setHorizontalAlignment(JLabel.CENTER);
        panel.add(titleLabel, BorderLayout.NORTH);

        return panel;
    }
    private static void displayImage(File imageFile, JPanel panel) {
        ImageIcon icon = new ImageIcon(imageFile.getAbsolutePath());
        Image image = icon.getImage();
        Image scaledImage = image.getScaledInstance(panel.getWidth(), panel.getHeight(), Image.SCALE_SMOOTH);
        ImageIcon scaledIcon = new ImageIcon(scaledImage);
        JLabel label = new JLabel(scaledIcon);
        panel.removeAll();
        panel.add(label);
        panel.revalidate();
        panel.repaint();
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(new SubstanceGeminiLookAndFeel());
                createAndShowGUI();
            } catch (UnsupportedLookAndFeelException e) {
                e.printStackTrace();
            }
        });
        //        javax.swing.SwingUtilities.invokeLater(new Runnable() {
//            public void run() {
//                createAndShowGUI();
//            }
//        });
    }
}

 

标签:IOException,return,String,API,static,图像处理,import,new,百度
From: https://www.cnblogs.com/liyiyang/p/17929197.html

相关文章

  • API文档生成!超好用API调试工具
    在数字化时代,API已经成为了应用程序之间进行通信的关键桥梁。随着API的普及和复杂性的增加,API研发和管理也面临着越来越多的挑战。为了更好地应对这些挑战,Apipost提供了一整套API研发工具,包括API设计、API调试、API文档和API自动化测试等功能。本文将深入介绍Apipost的优势和特点,助......
  • 基于百度API的文本翻译器实现
    软件构造的小实验,现给出源码造福未来学弟依赖<!--https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp--><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.9.1</......
  • Spring Boot学习随笔- RestFul API(@RestController、@RequestBody、@PathVariable),使用
    学习视频:【编程不良人】2021年SpringBoot最新最全教程第十六章、RestFulAPI什么是RESTREST全称是ResourceRepresentationalStateTransfer,中文意思是表述性状态转移,它首次出现在2000年RoyFielding的博士论文中,RoyFielding是HTTP规范的主要编写者之一。他在论文中表......
  • API文档生成!超好用API调试工具
    在数字化时代,API已经成为了应用程序之间进行通信的关键桥梁。随着API的普及和复杂性的增加,API研发和管理也面临着越来越多的挑战。为了更好地应对这些挑战,Apipost提供了一整套API研发工具,包括API设计、API调试、API文档和API自动化测试等功能。本文将深入介绍Apipost的优势和特点,......
  • 从八字命运API接口获取您的未来走向
     随着科技的快速发展和人们对个人命运的关注,越来越多的人开始寻找各类方法来预测自己的未来走向。而其中,八字预测是一种古老而又传统的方法,通过计算生辰八字,从五行八字中揭示出个人的命运走势。在这个过程中,挖数据平台提供了一款免费算命的API接口,为用户提供了便捷的命运预测服......
  • 4、zabbix 调用API 发送邮件,告警周报统计
    #coding=utf-8importrequests,json,codecs,datetime,time,pandasfromemailimportencodersfromemail.headerimportHeaderfromemail.mime.textimportMIMETextfromemail.utilsimportparseaddrfromsmtplibimportSMTPimportsmtplibApiUrl='http://......
  • 百度网盘(百度云)SVIP超级会员共享账号每日更新(2023.12.26)
    合集-网盘(20) 1.百度网盘(百度云)SVIP超级会员共享账号每日更新(2023.11.17)11-182.记录一次自己写的百度网盘不限速下载脚本11-183.百度网盘(百度云)SVIP超级会员共享账号每日更新(2023.11.20)11-214.百度网盘(百度云)SVIP超级会员共享账号每日更新(2023.11.21)11-215.百度网......
  • 淘宝/天猫商品API:实时数据获取与安全隐私保护的指南
    一、引言随着电子商务的快速发展,淘宝/天猫等电商平台已成为商家和消费者的重要交易场所。对于电商企业而言,实时掌握店铺商品的销售情况、库存状态等信息至关重要。然而,手动管理和更新商品信息既费时又费力。因此,淘宝/天猫提供的商品API成为商家实时获取商品数据的关键工具。本文将......
  • 免费IDEA插件推荐-Apipost-Helper
    IDEA插件市场中的API调试插件不是收费(FastRequest)就是不好用(apidoc、apidocx等等)今天给大家介绍一款国产的API调试插件:Apipost-Helper,完全免费且好看好用!这款插件由Apipost团队开发的,其官方介绍是:用于IDEA项目快速生成API文档,快速查询接口、接口代码功能,并支持在IDEA中进行API调......
  • ArcGIS API for JavaScript 4.x 免登录调用arcgis online私有服务
    APIkeys|ArcGISDevelopers 前言 本来以为普通用户调用服务只能依靠登录,仔细研究了一下可以通过key来实现免登录调用服务。背景最近在做一个BIM结合GIS的Demo,先通过arcgispro将.rvt文件配准到实际位置,然后打包成slpk文件,拖拽到arcgisonline发布出来,最后在前端加载。 ......