Java图片转Base64
2021/11/22 14:09:56
本文主要是介绍Java图片转Base64,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package org.jeecg.common.util; import org.apache.commons.codec.binary.Base64; import sun.misc.BASE64Decoder; import java.io.*; public class ImgBase64 { /** * 将图片转换成Base64编码 * @param imgFile 待处理图片 * @return */ 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 Base64.encodeBase64String(data); } /** * 对字节数组字符串进行Base64解码并生成图片 * @param imgStr 图片数据 * @param imgFilePath 保存图片全路径地址 * @return */ public static boolean generateImage(String imgStr, String imgFilePath) { // if (imgStr == null) // 图像数据为空 return false; 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(imgFilePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } }
调用: String url= "D:\\1.jpg";// 待处理的图片 String imgbese = getImgStr(url); String img_path="data:image/jpeg;base64,"+imgbese ; String url= "D:\\1.jpg";// 新生成的图片 generateImage(imgbese, url);
jar包: <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.13</version> </dependency>
这篇关于Java图片转Base64的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-19环境变量处理课程:新手入门教程
- 2024-09-19接口模块封装课程:新手入门指南
- 2024-09-19请求动作封装课程:新手入门教程
- 2024-09-19拖拽表格课程:新手入门指南
- 2024-09-19页面权限课程:新手必学的权限管理入门教程
- 2024-09-19如何正确主动登出课程:新手必读教程
- 2024-09-19Element-Plus课程:新手入门与初级教程
- 2024-09-19Token处理入门教程:新手必看指南
- 2024-09-19如何应对被动登出课程的情况:新手必读指南
- 2024-09-19打包优化课程:初学者的必备指南