public class ImgToBase64Util {
/**
* 将图片转成Base64编码
* @param imgFile 待处理图片
* @return
*/
public String getImgStr(String imgFile){
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try {
in = new FileInputStream(imgFile);
System.out.println("in:"+in);
data = new byte[in.available()];
in.read(data);
in.close();
return new String(Base64.encodeBase64(data));
} catch (IOException e) {
//e.printStackTrace();
return null;
}
}
/**
* 对字节数组字符串进行Base64解码并生成图片
* @param imgStr 图片数据
* @param imgFilePath 保存图片全路径地址
* @return
*/
public boolean generateImage(String imgStr,String imgFilePath){
if (imgStr == null){
return false;
}
try{
byte[] b = Base64.decodeBase64(imgStr);
for (int i=0;i<b.length;i++){
if (b[i]<0){
//调整异常数据
b[i]+=256;
}
}
//生成图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e){
return false;
}
}
public static void main(String[] args) {
ImgToBase64Util img = new ImgToBase64Util();
String s = "";
String imgFilePath = "D:\\Desktop\\8.1.1.jpg";
img.generateImage(s,imgFilePath);
}
}
图片转换成base64,再转换成图片
最新推荐文章于 2025-03-30 00:00:23 发布
文章描述了一个Java类ImgToBase64Util,包含两个方法:将图片转换为Base64编码和对Base64编码的字节数组解码并生成图片。示例展示了如何使用这些方法进行操作。

2192

被折叠的 条评论
为什么被折叠?



