从Base64编码转换为图⽚⽂件package luckyclient.utils;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Base64Image {
public static void main(String[] args) {
// 测试从Base64编码转换为图⽚⽂件
String strImg = "data:image/jpeg;base64,/9j/P/9k=";
GenerateImage(strImg, "D:\\wangyc.jpg");
// // 测试从图⽚⽂件转换为Base64编码
// System.out.println(GetImageStr("d:\\wangyc.jpg"));
}
//
// public static String GetImageStr(String imgFilePath) {// 将图⽚⽂件转化为字节数组字符串,并对其进⾏Base64编码处理// byte[] data = null;
//
// // 读取图⽚字节数组
// try {
// InputStream in = new FileInputStream(imgFilePath);
// data = new byte[in.available()];
// in.read(data);
// in.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// // 对字节数组Base64编码
// BASE64Encoder encoder = new BASE64Encoder();
// de(data);// 返回Base64编码过的字节数组字符串
// }
public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进⾏Base64解码并⽣成图⽚ if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// ⽣成jpeg图⽚
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
string字符串转化数组out.close();
return true;
} catch (Exception e) {
return false;
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论