目前还存在一些小问题,还得改改
package com.example;标签:增强,java,String,void,private,import,new,优化,图篇 From: https://www.cnblogs.com/mine-my/p/17900153.html
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class tuxiang extends JFrame {
private static final long serialVersionUID = 1L;
public static final String API_KEY = "TggSZoWYfVLpaGbezMzf2opT";
public static final String SECRET_KEY = "eF9UfmITtR0EUDFkDMyHyCcbKGHe9j8Y";
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
private JLabel imageLabel;
private JButton chooseButton;
private JButton processButton;
private String selectedImagePath;
public tuxiang() {
setTitle("Image Processing App");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initializeComponents();
setLayout(new BorderLayout());
add(imageLabel, BorderLayout.CENTER);
add(chooseButton, BorderLayout.WEST);
add(processButton, BorderLayout.EAST);
}
private void initializeComponents() {
imageLabel = new JLabel();
chooseButton = new JButton("Choose Image");
processButton = new JButton("Process Image");
chooseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
chooseImage();
}
});
processButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
processImage();
}
});
}
//用来选择文件位置
private void chooseImage() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
selectedImagePath = selectedFile.getAbsolutePath();
displayImage(selectedImagePath);
}
}
private void displayImage(String imagePath) {
ImageIcon icon = new ImageIcon(imagePath);
Image image = icon.getImage().getScaledInstance(300, 300, Image.SCALE_SMOOTH);
imageLabel.setIcon(new ImageIcon(image));
}
private void processImage() {
if (selectedImagePath != null && !selectedImagePath.isEmpty()) {
try {
String base64Image = getFileContentAsBase64(selectedImagePath, true);
String processedImage = processImageWithBaiduAPI(base64Image);
System.out.println(processedImage);
displayImage(processedImage);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Image processing failed: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(this, "Please choose an image first.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
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 String processImageWithBaiduAPI(String base64Image) throws Exception {
String s1="image=";
String ss=s1+base64Image;
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, ss);
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();
Response response = HTTP_CLIENT.newCall(request).execute();
return (response.body().string());
// Assuming there's a "processed_image" field in the response
}
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();
try {
return new JSONObject(response.body().string()).getString("access_token");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new tuxiang().setVisible(true);
}
});
}
}