关于JAVA11中图片与BASE64相互转换的实现
作者:一个不想学习的程序员
这篇文章主要介绍了关于JAVA11中图片与BASE64相互转换的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
由于jdk 1.8 之后sun.misc 包下的 BASE64Decode的依赖 被移除
我们需要在自己的项目中引入EncodeUtils 工具类 帮助我们进行转换
public class EncodeUtils {
private static final String DEFAULT_URL_ENCODING = "UTF-8";
/**
* Base64编码.
*/
public static String base64Encode(byte[] input) {
return new String(Base64.encodeBase64(input));
}
/**
* Base64解码.
*/
public static byte[] base64Decode(String input) {
return Base64.decodeBase64(input);
}
}
在项目中测试
直接调用工具类中的方法即可
/***
* <p>
* description: base64字符串转图片
* <p>
* @see
*/
static void base64StringToImage(String base64String) {
try {
byte[] bytes1 = EncodeUtils.base64Decode(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 = ImageIO.read(bais);
File f1 = new File("F:/wpcache/test/test.jpg");
ImageIO.write(bi1, "jpg", f1);
} catch (IOException e) {
e.printStackTrace();
}
}
/***
* <p>
* description:图片转base64字符串:
* <p>
* @see
*/
public static String getImgStr(String imgFile) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return EncodeUtils.base64Encode(data);
}
在main方法中运行
public static void main(String[] args) {
String base64Str = getImgStr("F:/wpcache/2.jpg");
System.out.println(base64Str);
base64StringToImage(base64Str);
}
运行结果
图片转BASE64 效果图

BASE64 转图片 效果图
(注:这个生成的图片路径就是自己在base64StringToImage 方法中的路径)

到此这篇关于关于JAVA11中图片与BASE64相互转换的实现的文章就介绍到这了,更多相关JAVA11图片与BASE64相互转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
