2024.11.24
实验二:百度图像增强与特效SDK实验
一、实验要求
任务一:下载配置百度图像增强与特效的Java相关库及环境(占10%)。
任务二:了解百度图像增强与特效相关功能并进行总结(占20%)。
任务三:完成图像增强GUI相关功能代码并测试调用,要求上传自己的模糊照片进行图像增强(占30%)。
任务四:完成图像特效GUI相关功能代码并测试调用,要求上传自己的照片进行图像特效(占30%)。
二、实验步骤
任务一:下载配置百度图像增强与特效的Java相关库及环境。
在百度智能云中创建一个新的项目,获取新的API Key和SerceKey
在获取Access Token页面查看需要导入的依赖
任务二:了解百度图像增强与特效相关功能并进行总结。
百度图像可以满足网络营销、广告活动等多种业务需求,并且提供了Java、PHP、Python等多种语言的SDK文档,方便开发者集成和使用。百度图像增强与特效接口能力丰富,能够提供业界领先的图像处理效果,并且具有灵活易用的特点。通过这些功能,开发者可以在应用程序中实时处理用户上传的图像,如社交媒体、相册应用等,提高图像质量、美化照片、个性化效果等方面的应用。
package org.example.baidu;
import okhttp3.*;
import org.json.JSONObject;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import javax.imageio.ImageIO;
class PhotoChangeGui {
public static final String API_KEY = "ddtWLFNWlAn1LgsFEqAlkll3";
public static final String SECRET_KEY = "RVomib4VY5HTTuX9Bb4RUgUEmprZDX0k";
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGUI());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("图片处理工具");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLayout(new FlowLayout());
JComboBox<String> effectBox = new JComboBox<>();
effectBox.addItem("人物动漫化");
effectBox.addItem("图像清晰度增强");
JButton uploadButton = new JButton("选择图片");
JButton processButton = new JButton("处理图像");
JLabel originalImageLabel = new JLabel("选择的图片显示在这里");
JLabel processedImageLabel = new JLabel("处理后的图片显示在这里");
// 选择图片
uploadButton.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
String selectedFile = fileChooser.getSelectedFile().getAbsolutePath();
System.out.println(selectedFile);
displayImage(selectedFile, originalImageLabel);
}
});
// 处理图片
processButton.addActionListener(e -> {
String selectedFile = (String) originalImageLabel.getClientProperty("selectedFile");
if (selectedFile != null) {
try {
String imageBase64 = getFileContentAsBase64(selectedFile, true);
String accessToken = getAccessToken();
String responseBody;
if (effectBox.getSelectedItem().equals("人物动漫化")) {
responseBody = sendImageToApi(imageBase64, accessToken);
} else {
responseBody = PhotoApi(imageBase64, accessToken);
}
displayProcessedImage(responseBody, processedImageLabel);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, "处理图片时发生错误:" + ex.getMessage());
}
} else {
JOptionPane.showMessageDialog(frame, "请先选择一张图片");
}
});
frame.add(effectBox);
frame.add(uploadButton);
frame.add(processButton);
frame.add(originalImageLabel);
frame.add(processedImageLabel);
frame.setVisible(true);
}
private static void displayImage(String imagePath, JLabel label) {
try {
BufferedImage img = ImageIO.read(Files.newInputStream(Paths.get(imagePath)));
ImageIcon icon = new ImageIcon(img.getScaledInstance(400, 400, Image.SCALE_SMOOTH));
label.setIcon(icon);
label.setText(null);
label.putClientProperty("selectedFile", imagePath); // 保存选择的文件路径
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "无法加载图片:" + e.getMessage());
}
}
private static void displayProcessedImage(String responseBody, JLabel label) {
try {
JSONObject jsonResponse = new JSONObject(responseBody);
if (!jsonResponse.has("image")) {
throw new IOException("响应中没有找到 'image' 键");
}
String base64Image = jsonResponse.getString("image");
Base64.Decoder decoder = Base64.getDecoder();
byte[] imageBytes = decoder.decode(base64Image);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
ImageIcon icon = new ImageIcon(image.getScaledInstance(400, 400, Image.SCALE_SMOOTH));
label.setIcon(icon);
label.setText(null);
saveImage(image, "C:\\Users\\wr200\\Desktop\\01\\processed_image.png");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "显示处理后的图片时发生错误:" + e.getMessage());
}
}
static String sendImageToApi(String imageBase64, String accessToken) throws IOException {
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "image=" + imageBase64);
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();
try (Response response = HTTP_CLIENT.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
return response.body().string();
}
}
static String PhotoApi(String imageBase64, String accessToken) throws IOException {
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "image=" + imageBase64);
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();
try (Response response = HTTP_CLIENT.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
return response.body().string();
}
}
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;
}
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();
try (Response response = HTTP_CLIENT.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
return new JSONObject(response.body().string()).getString("access_token");
}
}
private static void saveImage(BufferedImage image, String filePath) {
try {
// 创建目标文件
File outputFile = new File(filePath);
// 保存图像
ImageIO.write(image, "png", outputFile);
System.out.println("图片成功保存到: " + outputFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "保存图片时发生错误:" + e.getMessage());
}
}
}