软件构造 实验二
实验二:百度图像增强与特效SDK实验(2023.12.6日完成)
任务一:下载配置百度图像增强与特效的Java相关库及环境(占10%)。
任务二:了解百度图像增强与特效相关功能并进行总结(占20%)。
任务三:完成图像增强GUI相关功能代码并测试调用,要求上传自己的模糊照片进行图像增强(占30%)。
任务四:完成图像特效GUI相关功能代码并测试调用,要求上传自己的照片进行图像特效(占30%)。
实验总结:(占10%)
实验效果样例图:
参考资料:https://cloud.baidu.com/product/imageprocess
https://cloud.baidu.com/doc/IMAGEPROCESS/index.html
package org.example.test2;
import okhttp3.*;
import org.json.JSONObject;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.net.URLEncoder;
public class App {
private 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(600, 300);
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel imagePanel = new JPanel(new GridLayout(1, 2));
JLabel originalLabel = new JLabel();
JLabel enhancedLabel = new JLabel();
imagePanel.add(originalLabel);
imagePanel.add(enhancedLabel);
JPanel buttonPanel = new JPanel();
JButton enhanceButton = new JButton("图像动漫化");
JButton chooseFileButton = new JButton("选择图片");
chooseFileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
chooseFile(originalLabel);
}
});
enhanceButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
enhanceImages(originalLabel, enhancedLabel);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
buttonPanel.add(chooseFileButton);
buttonPanel.add(enhanceButton);
mainPanel.add(imagePanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.NORTH);
frame.getContentPane().add(mainPanel);
frame.setVisible(true);
}
private static void chooseFile(JLabel originalLabel) {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "jpeg", "png", "gif");
fileChooser.setFileFilter(filter);
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
String filePath = fileChooser.getSelectedFile().getAbsolutePath();
ImageIcon originalImageIcon = new ImageIcon(filePath);
// 自适应显示在标签中
int width = originalLabel.getWidth();
int height = originalLabel.getHeight();
originalLabel.setIcon(new ImageIcon(originalImageIcon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH)));
}
}
private static void enhanceImages(JLabel originalLabel, JLabel enhancedLabel) throws IOException {
// 获取用户选择的原始图像路径
String filePath = getUserSelectedFilePath(originalLabel);
if (filePath == null) {
JOptionPane.showMessageDialog(null, "请选择图片");
return;
}
// 读取图像文件并将其转换为 Base64
boolean urlEncode = true;
String imageBase64 = getFileContentAsBase64(filePath, urlEncode);
// 创建包含 Base64 编码图像的请求体
RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), "image=" + imageBase64);
// 发送 API 请求
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=24.025f806eb27acb5cf0cf11a5817a612c.2592000.1705069401.282335-44919292")
.method("POST", body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Accept", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
// 处理 API 响应
String responseBody = response.body().string();
JSONObject jsonResponse = new JSONObject(responseBody);
// 从 JSON 中提取增强后的图像信息
String enhancedImageBase64 = jsonResponse.optString("image", "");
// 构造输出文件的路径,与输入文件在同一目录下,文件名为enhanced_image.jpg
String outputFileName = "enhanced_image.jpg";
String outputPath = "C://Users//dell//Pictures//Saved Pictures//img"+outputFileName;
// 将Base64编码转换为图像并导出
exportBase64Image(enhancedImageBase64, outputPath);
// 显示增强后的图像
ImageIcon enhancedImageIcon = new ImageIcon(outputPath);
// 自适应显示在标签中
int width = originalLabel.getWidth();
int height = originalLabel.getHeight();
enhancedLabel.setIcon(new ImageIcon(enhancedImageIcon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH)));
// 显示弹窗消息
// JOptionPane.showMessageDialog(null, "图像保存至:" + outputPath);
}
private static String getUserSelectedFilePath(JLabel originalLabel) {
Icon icon = originalLabel.getIcon();
if (icon != null && icon instanceof ImageIcon) {
Image image = ((ImageIcon) icon).getImage();
String description = "User Selected Image";
MediaTracker tracker = new MediaTracker(originalLabel);
tracker.addImage(image, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 直接返回图像的路径,而无需保存到临时文件
try {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
// 创建临时文件并获取路径
Path tempPath = Files.createTempFile("temp_selected_image", ".jpg");
ImageIO.write(bufferedImage, "jpg", tempPath.toFile());
// 返回临时文件的路径
return tempPath.toString();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
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;
}
private static void exportBase64Image(String base64String, String outputPath) throws IOException {
// 将Base64字符串解码为字节数组
byte[] decodedBytes = Base64.getDecoder().decode(base64String);
// 将字节数组写入输出文件
try (FileOutputStream outputStream = new FileOutputStream(outputPath)) {
outputStream.write(decodedBytes);
}
}
}