11.8 图像增强与动漫化二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /* * 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); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | 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; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | 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 ); }); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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 { } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!