package tuxiang; import okhttp3.*; 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.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Base64; import java.net.URLEncoder; public class ImageConverter extends JFrame implements ActionListener { private JTextField imageField; private JLabel originImageLabel; private JLabel resultImageLabel; public static final String API_KEY = "ldQefiX4omFzf2e3dDEESqGG"; public static final String SECRET_KEY = "0slIQkoLw1QYk4AvAbMe3NFA03u2P6It"; static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build(); public ImageConverter() { // 设置窗口标题 setTitle("Image Converter"); // 设置窗口大小 setSize(1200, 700); // 设置窗口关闭时退出程序 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 创建主面板 JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); // 创建选择文件按钮和文本框 JButton selectButton = new JButton("选择图片"); selectButton.addActionListener(this); imageField = new JTextField(); imageField.setEditable(false); // 显示原始图片的标签 originImageLabel = new JLabel(); // 创建转换按钮 JButton convertButton = new JButton("图片特效"); convertButton.addActionListener(this); // 创建结果图片标签 resultImageLabel = new JLabel(); // 添加组件到主面板 panel.add(selectButton, BorderLayout.NORTH); panel.add(imageField, BorderLayout.CENTER); panel.add(originImageLabel, BorderLayout.WEST); panel.add(convertButton, BorderLayout.SOUTH); panel.add(resultImageLabel, BorderLayout.EAST); // 将主面板添加到窗口 add(panel); } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("选择图片")) { JFileChooser fileChooser = new JFileChooser(); int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { String imagePath = fileChooser.getSelectedFile().getAbsolutePath(); imageField.setText(imagePath); showOriginImage(imagePath); } } else if (e.getActionCommand().equals("图片特效")) { String imagePath = imageField.getText(); try { String base64Image = getFileContentAsBase64(imagePath, true); String convertedImage = convertImage(base64Image); showResultImage(convertedImage); } catch (IOException ex) { ex.printStackTrace(); } } } private void showOriginImage(String imagePath) { try { BufferedImage image = ImageIO.read(new File(imagePath)); if (image != null) { ImageIcon icon = new ImageIcon(image.getScaledInstance(450, 450, Image.SCALE_SMOOTH)); originImageLabel.setIcon(icon); } else { System.err.println("Error: Failed to load image"); } } catch (IOException e) { e.printStackTrace(); System.err.println("Error loading image: " + e.getMessage()); } } private String convertImage(String base64Image) throws IOException { MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = RequestBody.create(mediaType, "type=anime&image=" + base64Image); 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(); String responseBody = response.body().string(); JSONObject jsonResponse = new JSONObject(responseBody); return jsonResponse.getString("image"); } private void showResultImage(String base64Image) { byte[] imageBytes = Base64.getDecoder().decode(base64Image); try { BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes)); ImageIcon icon = new ImageIcon(image.getScaledInstance(450, 450, Image.SCALE_SMOOTH)); resultImageLabel.setIcon(icon); } catch (IOException e) { e.printStackTrace(); } } /** * 获取文件base64编码 * * @param path 文件路径 * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true * @return base64编码信息,不带文件头 * @throws IOException IO异常 */ 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; } /** * 从用户的AK,SK生成鉴权签名(Access Token) * * @return 鉴权签名(Access Token) * @throws IOException IO异常 */ private 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"); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { ImageConverter gui = new ImageConverter(); gui.setVisible(true); }); } }
标签:总结,java,String,每日,IOException,12.13,import,new,image From: https://www.cnblogs.com/louwangshayu/p/17900046.html