/*
* Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
*/
package org.example;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
/**
* Json工具类.
*/
public class GsonUtils {
private static Gson gson = new GsonBuilder().create();
public static String toJson(Object value) {
return gson.toJson(value);
}
public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
return gson.fromJson(json, classOfT);
}
public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
return (T) gson.fromJson(json, typeOfT);
}
}
package org.example;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* http 工具类
*/
public class HttpUtil {
public static String post(String requestUrl, String accessToken, String params)
throws Exception {
String contentType = "application/x-www-form-urlencoded";
return HttpUtil.post(requestUrl, accessToken, contentType, params);
}
public static String post(String requestUrl, String accessToken, String contentType, String params)
throws Exception {
String encoding = "UTF-8";
if (requestUrl.contains("nlp")) {
encoding = "GBK";
}
return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
}
public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
throws Exception {
String url = requestUrl + "?access_token=" + accessToken;
return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
}
public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
throws Exception {
URL url = new URL(generalUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 得到请求的输出流对象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(params.getBytes(encoding));
out.flush();
out.close();
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> headers = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
System.err.println(key + "--->" + headers.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
in = new BufferedReader(
new InputStreamReader(connection.getInputStream(), encoding));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
System.err.println("result:" + result);
return result;
}
}
package org.example;
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.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class ImageProcessingUI extends JFrame {
private JTextField filePathField;
private JButton selectFileButton;
private JButton processButton;
private JLabel originalImageLabel;
private JLabel processedImageLabel;
private String selectedAction; // "anime" 或 "enhance"
public ImageProcessingUI() {
setTitle("图像处理");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// 创建顶部面板
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(3, 2, 5, 5)); // 添加间距
JLabel filePathLabel = new JLabel("图片路径:");
filePathField = new JTextField();
filePathField.setColumns(30);
selectFileButton = new JButton("选择图片");
selectFileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(ImageProcessingUI.this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
filePathField.setText(selectedFile.getAbsolutePath());
displayOriginalImage(selectedFile);
}
}
});
JButton actionSelectButton = new JButton("选择操作");
actionSelectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String action = (String) JOptionPane.showInputDialog(ImageProcessingUI.this, "请选择操作:",
"操作选择", JOptionPane.QUESTION_MESSAGE, null, new Object[]{"动漫化", "清晰度增强"}, "动漫化");
selectedAction = action;
}
});
processButton = new JButton("处理");
processButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String filePath = filePathField.getText();
if (filePath.isEmpty()) {
JOptionPane.showMessageDialog(ImageProcessingUI.this, "请选择一个图片文件。", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
String result = processImage(filePath);
if (result != null) {
JOptionPane.showMessageDialog(ImageProcessingUI.this, "结果已保存。", "成功", JOptionPane.INFORMATION_MESSAGE);
displayProcessedImage(new File(result));
} else {
JOptionPane.showMessageDialog(ImageProcessingUI.this, "处理图片失败。", "错误", JOptionPane.ERROR_MESSAGE);
}
}
});
topPanel.add(filePathLabel);
topPanel.add(filePathField);
topPanel.add(selectFileButton);
topPanel.add(actionSelectButton);
topPanel.add(processButton);
// 创建中间面板用于显示图像
JPanel imagePanel = new JPanel();
imagePanel.setLayout(new GridLayout(1, 2, 10, 10)); // 添加间距
originalImageLabel = new JLabel("原始图像");
originalImageLabel.setHorizontalAlignment(SwingConstants.CENTER);
originalImageLabel.setBorder(BorderFactory.createTitledBorder("原始图像"));
processedImageLabel = new JLabel("处理后的图像");
processedImageLabel.setHorizontalAlignment(SwingConstants.CENTER);
processedImageLabel.setBorder(BorderFactory.createTitledBorder("处理后的图像"));
imagePanel.add(originalImageLabel);
imagePanel.add(processedImageLabel);
panel.add(topPanel, BorderLayout.NORTH);
panel.add(imagePanel, BorderLayout.CENTER);
add(panel);
// 设置背景颜色
panel.setBackground(Color.LIGHT_GRAY);
topPanel.setBackground(Color.LIGHT_GRAY);
imagePanel.setBackground(Color.LIGHT_GRAY);
}
private void displayOriginalImage(final File file) {
SwingUtilities.invokeLater(() -> {
try {
BufferedImage originalImage = ImageIO.read(file);
ImageIcon icon = new ImageIcon(resizeImage(originalImage, 350, 350));
originalImageLabel.setIcon(icon);
originalImageLabel.setText(""); // 清除文本
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "加载原始图像失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
});
}
private void displayProcessedImage(final File file) {
SwingUtilities.invokeLater(() -> {
try {
BufferedImage processedImage = ImageIO.read(file);
ImageIcon icon = new ImageIcon(resizeImage(processedImage, 350, 350));
processedImageLabel.setIcon(icon);
processedImageLabel.setText(""); // 清除文本
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "加载处理后的图像失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
}
});
}
private BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
Image temp = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = resizedImage.createGraphics();
g2d.drawImage(temp, 0, 0, null);
g2d.dispose();
return resizedImage;
}
public String processImage(String filePath) {
try {
byte[] imgData = Files.readAllBytes(Paths.get(filePath));
String imgStr = Base64.getEncoder().encodeToString(imgData);
String imgParam = URLEncoder.encode(imgStr, "UTF-8");
String param = "image=" + imgParam;
// 获取access_token
String accessToken = AuthService.getAuth(API_KEY, SECRET_KEY);
String url;
if ("动漫化".equals(selectedAction)) {
url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime";
} else {
url = "https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance";
}
String result = HttpUtil.post(url, accessToken, param);
System.out.println(result);
// 解析返回的结果
if (result != null && !result.isEmpty()) {
// 假设返回的JSON中包含一个名为"image"的字段,该字段包含Base64编码的图像数据
String base64EncodedString = parseBase64FromResult(result);
// 解码Base64字符串
byte[] decodedBytes = Base64.getDecoder().decode(base64EncodedString);
// 指定输出文件名
String outputFilePath = "output_image.jpg"; // 或者其他格式,比如.png等
// 将解码后的字节写入到指定的文件中
Files.write(Paths.get(outputFilePath), decodedBytes);
System.out.println("图像已保存到:" + outputFilePath);
return outputFilePath;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String parseBase64FromResult(String result) {
// 这里假设返回的JSON格式如下:
// {"log_id":1234567890,"image":"base64_encoded_string"}
// 你需要根据实际返回的JSON格式进行解析
// 可以使用JSON库(如Gson或Jackson)来解析JSON
// 这里简化处理,直接提取"image"字段的值
int startIndex = result.indexOf("\"image\":\"") + 9;
int endIndex = result.indexOf("\"", startIndex);
return result.substring(startIndex, endIndex);
}
// 百度AI平台的凭证信息
public static final String API_KEY = "68ny2VNI0OXN7YTgnzk8Rqya";
public static final String SECRET_KEY = "gPJUrulUE9xIBXoPXLB6BMbE6lSw8Kzy";
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
ImageProcessingUI frame = new ImageProcessingUI();
frame.setVisible(true);
});
}
}
package org.example;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class TokenUtil {
private static final String API_KEY = "68ny2VNI0OXN7YTgnzk8Rqya";
private static final String SECRET_KEY = "gPJUrulUE9xIBXoPXLB6BMbE6lSw8Kzy";
public static String getAccessToken() throws Exception {
String requestUrl = "https://aip.baidubce.com/oauth/2.0/token";
String params = "grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY;
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(params.getBytes().length);
conn.getOutputStream().write(params.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 使用Gson解析JSON响应
JsonObject jsonResponse = JsonParser.parseString(response.toString()).getAsJsonObject();
String accessToken = jsonResponse.get("access_token").getAsString();
return accessToken;
}
public static void main(String[] args) throws Exception {
}
}