java自带BASE64工具进行图片和字符串转换

java自带BASE64工具进行图片和字符串转换

java自带BASE64工具进行图片和字符串转换

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; public class Base64Test {
public static void main(String[] args) throws Exception{
File inputFile = new File("src/test.jpg");// 放在src文件夹下 待处理的图片
String strImg = null;
if(inputFile.exists()){
strImg = getImageStr(inputFile);
System.out.println(inputFile.getPath()+"转换后的字符串:\n"+strImg);
} File outputFile = new File("src/testCopy.jpg");// 即将在src文件夹下 生成的图片
generateImage(outputFile,strImg);
} /**
* 图片转化成base64字符串
* @param inputFile 源图片文件路径
* @return
*/
public static String getImageStr(File inputFile) throws Exception{// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
in = new FileInputStream(inputFile);
data = new byte[in.available()];
in.read(data);
in.close();
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
} /**
* base64字符串转化成图片
* @param outputFile 输出目标图片
* @param imgStr BASE64字符串
* @return
*/
public static boolean generateImage( File outputFile ,String imgStr ) throws Exception{ // 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) // 图像数据为空
return false;
// imgStr = "";
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成jpg图片
OutputStream out = new FileOutputStream(outputFile);
out.write(b);
out.flush();
out.close();
System.out.println("通过BASE64字符串\n"+imgStr+"\n 生成"+outputFile.getPath());
return true;
} catch (Exception e) {
return false;
}
}
}

打印结果

src\test.jpg转换后的BASE64字符串:
iVBORw0KGgoAAAANSUhEUgAAAFoAAAAZAQMAAACLqquDAAAABlBMVEUAAAD///+l2Z/dAAAAY0lE
QVR4nGNgIAOwf0DisDHg5DxA1mPAwMDfAONJANEBJA5DAkwPiAOTYTawYWCG6WF8kAaUYYRZfRio
h1kCicMA46QDjWb+AeVYAy1lg8kwgyywgHKcQQI3oJw0ZHfbMJAIALYtEHx6n3m7AAAAAElFTkSu
QmCC
通过BASE64字符串
iVBORw0KGgoAAAANSUhEUgAAAFoAAAAZAQMAAACLqquDAAAABlBMVEUAAAD///+l2Z/dAAAAY0lE
QVR4nGNgIAOwf0DisDHg5DxA1mPAwMDfAONJANEBJA5DAkwPiAOTYTawYWCG6WF8kAaUYYRZfRio
h1kCicMA46QDjWb+AeVYAy1lg8kwgyywgHKcQQI3oJw0ZHfbMJAIALYtEHx6n3m7AAAAAElFTkSu
QmCC
生成src\testCopy.jpg
04-14 18:13