import org.apache.commons.lang3.StringUtils; import org.apache.tomcat.util.codec.binary.Base64; import java.io.*; public class Base64Util { private static final LoggerUtil logger = LogFactory.getLogger(Base64Util.class); //图片转化成base64字符串 public static String GetImageStr(String imgFile) { //将图片文件转化为字节数组字符串,并对其进行Base64编码处理 byte[] data = null; //读取图片字节数组 try (InputStream in = new FileInputStream(imgFile);) { data = new byte[in.available()]; in.read(data); } catch (IOException e) { logger.info("Base64Util GetImageStr e:" + e.getLocalizedMessage()); } //返回Base64编码过的字节数组字符串 return Base64.encodeBase64String(data); } //base64字符串转化成图片 public static String GenerateImage(String imgStr, String fileName) { //对字节数组字符串进行Base64解码并生成图片 String imgUrl = ""; //图像数据为空 if (StringUtils.isBlank(imgStr)) return imgUrl; //Base64解码 byte[] b = Base64.decodeBase64(imgStr); for (int i = 0; i < b.length; ++i) { //调整异常数据 if (b[i] < 0) { b[i] += 256; } } //文件目录不存在则建立 File outFile = new File(CommonConstant.FILEPATH); if (!outFile.exists()) { outFile.mkdirs(); } //文件最终的存储位置 File dest = new File(CommonConstant.FILEPATH + fileName); //判断目标文件所在的目录是否存在 if (!dest.getParentFile().exists()) { //建立目录 if (!dest.getParentFile().mkdirs()) { return imgUrl; } } //新生成的图片 imgUrl = CommonConstant.FILEPATH + fileName; //这种写法不须要flush或者close 会自动关闭 FileOutputStream 实现了java中的java.lang.AutoCloseable接口。 try (OutputStream out = new FileOutputStream(CommonConstant.FILEPATH + fileName);) { out.write(b); } catch (Exception e) { logger.info("Base64Util GenerateImage e:" + e.getLocalizedMessage()); } finally { return imgUrl; } } }