使用Java,实现图片与Base64编码互转的程序
因工作需要,特意写段将图片与Base64编码实现互转的程序。本程序使用到sun.misc.BASE64Decoder.jar,请在网上自行下载此Jar包。或者单击下面链接: https://pan.baidu.com/s/1xRV-UL2JgjskHApuPoS2Og 提取码: ptij
转换代码参考如下:
package com.clzhang.util; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import Decoder.BASE64Decoder; import Decoder.BASE64Encoder; public class Base64Util { /** * 图片转化成Base64字符串,有异常返回null,并打印异常信息 * @param imgPath 图片物理路径 * @return BASE64编码格式字符串 */ public static String getImageStr(String imgPath) { InputStream in = null; byte[] data = null; String result = null; BASE64Encoder encoder = new BASE64Encoder(); try { in = new FileInputStream(imgPath); data = new byte[in.available()]; in.read(data); result = encoder.encode(data); } catch (IOException e) { e.printStackTrace(); } return result; } /** * base64字符串转化成图片,成功返回trur,有异常返回false * @param imgData Base64字符串 * @param imgFilePath 图片存放物理路径 * @return 成功与否 * @throws IOException */ @SuppressWarnings("finally") public static boolean generateImage(String imgData, String imgFilePath) throws IOException { // 对字节数组字符串进行Base64解码并生成图片 if (imgData == null) // 图像数据为空 return false; BASE64Decoder decoder = new BASE64Decoder(); OutputStream out = null; try { out = new FileOutputStream(imgFilePath); byte[] b = decoder.decodeBuffer(imgData); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } out.write(b); out.close(); return true; } catch (IOException e) { e.printStackTrace(); } return false; } public static void main(String[] args) throws Exception { String imagePath = "D:\\TDDOWNLOAD\\code\\mycode.gif"; String imagePath2 = "D:\\TDDOWNLOAD\\code\\mycode2.gif"; String base64Str = getImageStr(imagePath); System.out.println(base64Str); generateImage(base64Str, imagePath2); } }