package baidu.com.tupian;
import okhttp3.*;
import org.json.JSONObject;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class ImageEffectGUI {
// API Key 和 Secret Key
public static final String API_KEY = "SP3mEK87MwBGnxXsppHgDMt3";
public static final String SECRET_KEY = "M5AyIxOWiFuKb16qgW8MdrRNtq7UBdBH";
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
private JFrame frame;
private JLabel originalImageLabel;
private JLabel enhancedImageLabel;
public static void main(String[] args) {
// 创建和显示 GUI 窗口
EventQueue.invokeLater(() -> {
try {
ImageEffectGUI window = new ImageEffectGUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
public ImageEffectGUI() {
// 设置 GUI 窗口
frame = new JFrame("图像特效");
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
// 创建左边面板(显示原图)
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BorderLayout());
originalImageLabel = new JLabel("原图", JLabel.CENTER);
leftPanel.add(originalImageLabel, BorderLayout.CENTER);
frame.getContentPane().add(leftPanel, BorderLayout.WEST);
// 创建右边面板(显示特效图)
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BorderLayout());
enhancedImageLabel = new JLabel("特效图", JLabel.CENTER);
rightPanel.add(enhancedImageLabel, BorderLayout.CENTER);
frame.getContentPane().add(rightPanel, BorderLayout.CENTER);
// 创建上传按钮,上传图片并应用特效
JButton uploadButton = new JButton("上传图片");
uploadButton.addActionListener(e -> chooseImageAndApplyEffect());
JPanel bottomPanel = new JPanel();
bottomPanel.add(uploadButton);
frame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
}
/**
* 选择图片并应用卡通特效
*/
private void chooseImageAndApplyEffect() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("选择图片文件");
int returnValue = fileChooser.showOpenDialog(frame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
String selectedFilePath = selectedFile.getAbsolutePath();
try {
String accessToken = getAccessToken();
String enhancedImageBase64 = applyCartoonEffect(new File(selectedFilePath), accessToken);
// 显示原图
ImageIcon originalImageIcon = new ImageIcon(selectedFile.getAbsolutePath());
originalImageLabel.setIcon(originalImageIcon);
originalImageLabel.setText(null);
// 显示增强后的图像
saveBase64ToImage(enhancedImageBase64, "cartoon_image.jpg");
ImageIcon enhancedImageIcon = new ImageIcon("cartoon_image.jpg");
enhancedImageLabel.setIcon(enhancedImageIcon);
enhancedImageLabel.setText(null);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, "图像特效应用失败: " + ex.getMessage());
}
}
}
/**
* 获取百度 API 的 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();
JSONObject responseJson = new JSONObject(response.body().string());
return responseJson.getString("access_token");
}
/**
* 应用卡通特效
*
* @param imageFile 待处理的图像文件
* @param accessToken 获取的 Access Token
* @return 特效后的图像 Base64 编码
* @throws IOException IO 异常
*/
static String applyCartoonEffect(File imageFile, String accessToken) throws IOException {
// 将图片转换为 Base64 编码
byte[] imageBytes = Files.readAllBytes(imageFile.toPath());
String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);
// 对 Base64 字符串进行 URL 编码
String encodedImage = URLEncoder.encode(imageBase64, StandardCharsets.UTF_8.toString());
// 构建请求体
String requestBody = "image=" + encodedImage;
// 创建请求体
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, requestBody);
// 创建请求
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=" + accessToken)
.post(body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Accept", "application/json")
.build();
// 执行请求
Response response = HTTP_CLIENT.newCall(request).execute();
String responseBody = response.body().string();
// 打印返回的原始响应内容
System.out.println("Response: " + responseBody);
// 从响应中提取处理后的图像 Base64
JSONObject responseJson = new JSONObject(responseBody);
if (responseJson.has("image") && !responseJson.getString("image").isEmpty()) {
return responseJson.getString("image");
} else {
String errorMsg = responseJson.optString("error_msg", "未知错误");
throw new IOException("图像特效应用失败: " + errorMsg);
}
}
/**
* 将 Base64 编码的图像保存为图片文件
*
* @param base64Str Base64 编码的字符串
* @param outputPath 输出图片路径
*/
private void saveBase64ToImage(String base64Str, String outputPath) {
try {
byte[] imageBytes = Base64.getDecoder().decode(base64Str);
try (FileOutputStream fos = new FileOutputStream(outputPath)) {
fos.write(imageBytes);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人