2024.11.27

package baidu.com.tupian;

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

import java.awt.*;
import java.io.*;
import java.nio.file.Files;
import java.util.Base64;
import javax.swing.*;

public class Sample1 {
public static final String API_KEY = "4lI1pIf5ztMl5ZWyl6cMGXsj";
public static final String SECRET_KEY = "vCOfaGPIEzjLXdBjaZkuVUKGaUxsLjtH";

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

public static void main(String[] args) throws IOException {
File imageFile = new File("D:\\code\\实验二\\img.jpg");
String accessToken = getAccessToken();
String enhancedImageBase64 = enhanceImage(imageFile, accessToken);

// 将Base64编码的增强图像转换为图片并保存
saveBase64ToImage(enhancedImageBase64, "enhanced_image.jpg");

// 显示原图和增强后的图像
displayImages("D:\\code\\实验二\\img.jpg", "enhanced_image.jpg");
}

/**
* 从用户的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");
}

/**
* 提交图像进行增强
* @param imageFile 待增强的图像文件
* @param accessToken 获取的Access Token
* @return 增强后的图像Base64编码
* @throws IOException
*/
static String enhanceImage(File imageFile, String accessToken) throws IOException {
// 将图片转为Base64
byte[] imageBytes = Files.readAllBytes(imageFile.toPath());
String imageBase64 = Base64.getEncoder().encodeToString(imageBytes);

// 创建请求体
MediaType mediaType = MediaType.parse("application/json");
JSONObject jsonObject = new JSONObject();
jsonObject.put("image", imageBase64);

// 创建有效的 rectangle 参数(此时设置一个默认区域,表示修复图片的整个区域)
JSONArray rectangleArray = new JSONArray();
JSONObject rectangle = new JSONObject();
rectangle.put("left", 543);
rectangle.put("top", 25);
rectangle.put("width", 92); // 根据图像的实际尺寸调整
rectangle.put("height", 36); // 根据图像的实际尺寸调整
rectangleArray.put(rectangle);

jsonObject.put("rectangle", rectangleArray); // 将 rectangle 参数加入请求

// 打印请求的内容,帮助调试
System.out.println("Request Body: " + jsonObject.toString());

RequestBody body = RequestBody.create(mediaType, jsonObject.toString());
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rest/2.0/image-process/v1/inpainting?access_token=" + accessToken)
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();

// 执行请求并获取响应
Response response = HTTP_CLIENT.newCall(request).execute();
String responseBody = response.body().string();

// 打印返回的原始响应内容
System.out.println("Response: " + responseBody);

// 检查响应是否包含"image"字段
JSONObject responseJson = new JSONObject(responseBody);
if (responseJson.has("image") && !responseJson.getString("image").isEmpty()) {
return responseJson.getString("image");
} else {
// 如果没有"image"字段,打印错误信息
String errorMsg = responseJson.optString("error_msg", "未知错误");
throw new IOException("图像增强失败: " + errorMsg);
}
}

/**
* 将Base64编码的图像保存为图片文件
* @param base64Str Base64编码的图像字符串
* @param outputFilePath 输出文件路径
* @throws IOException
*/
static void saveBase64ToImage(String base64Str, String outputFilePath) throws IOException {
// 去掉Base64编码中的前缀部分
String imageData = base64Str.replaceFirst("data:image/.+;base64,", "");

// 解码Base64字符串为字节数组
byte[] imageBytes = Base64.getDecoder().decode(imageData);

// 写入文件
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
fos.write(imageBytes);
}
}

/**
* 显示原始图像和增强后的图像
* @param originalImagePath 原始图像文件路径
* @param enhancedImagePath 增强后的图像文件路径
*/
static void displayImages(String originalImagePath, String enhancedImagePath) {
// 创建图像标签显示图片
ImageIcon originalImageIcon = new ImageIcon(originalImagePath);
JLabel originalImageLabel = new JLabel(originalImageIcon);

ImageIcon enhancedImageIcon = new ImageIcon(enhancedImagePath);
JLabel enhancedImageLabel = new JLabel(enhancedImageIcon);

// 创建一个面板,将两个图像显示在同一窗口中
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
panel.add(originalImageLabel);
panel.add(enhancedImageLabel);

// 创建一个窗口显示图像
JFrame frame = new JFrame("图像增强");
frame.setLayout(new BorderLayout());
frame.setSize(1000, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel, BorderLayout.CENTER);
frame.setVisible(true);
}
}
posted @   我也不想的  阅读(2)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示