图片与字符串(base64编码)的转化

时间:2023-01-11 13:57:12
package com.demo;
import java.util.*;
import java.io.*;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ImageTra {

/*
* 有给定base64编码的字符串,抓化为图片
* 先经过解码生成字节数据(byte数组存储)
* 然后IO六输出
*
*/
public static boolean generateImg(String String, String path) throws IOException{
if (String == null){
return false;
}
else{
OutputStream out
= new FileOutputStream(path);
BASE64Decoder decoder
= new BASE64Decoder();

byte[] data = decoder.decodeBuffer(String);
out.write(data);
out.flush();
out.close();
return true;
}
}

/*
* 给定一张图片,经base64编码转化为字符串,
*
*/
public static String ImgToString(String path) throws IOException{
InputStream inputStream
= new FileInputStream(path);
//根据图片的字节大小定义byte数组
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
// base64加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//当前路径
// System.out.println(System.getProperty("user.dir"));
String string = ImgToString("test.png");
generateImg(string,
"same.png");

}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

}