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,再转换成图片
最新推荐文章于 2024-05-09 17:40:59 发布