软件编程
位置:首页>> 软件编程>> java编程>> Java将byte[]转图片存储到本地的案例

Java将byte[]转图片存储到本地的案例

作者:Curry_BB  发布时间:2021-08-30 08:19:12 

标签:@Slf4j注解,日志,输出

Java中,将字节数组转成图片的有很多种方式,今天在这里记录其中一种,方便以后查询,也可以提供给没有接触的童鞋做一个参考。

首先是将图片转成字节数组


import sun.misc.BASE64Encoder;
import java.io.*;

// 传入图片路径,获取图片
FileInputStream fis = new FileInputStream("/Users/curry/error.png");
BufferedInputStream bis = new BufferedInputStream(fis);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = fis.read(buff)) != -1) {
 bos.write(buff, 0, len);
}
// 得到图片的字节数组
byte[] result = bos.toByteArray();
// 将数组转为字符串
BASE64Encoder encoder = new BASE64Encoder();
String str = encoder.encode(result).trim();

将数组转为图片


import sun.misc.BASE64Decoder;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

BASE64Decoder decoder = new BASE64Decoder();
byte[] imgbyte = decoder.decodeBuffer("刚刚将字节数组转成的字符串");
OutputStream os = new FileOutputStream("/Users/curry/text.png");
os.write(imgbyte, 0, imgbyte.length);
os.flush();
os.close();

补充知识:java将图片转化为base64和base64转化为图片编码并保存在本地

我就废话不多说了,大家还是直接看代码吧~


public class Base64Convert {

/**
  * @Description: 图片转化成base64字符串
  * @param:  path
  * @Return:
  */
 public static String GetImageStr(String path)
 {
   //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
   //待处理的图片
   String imgFile = path;
   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();
   }
   //对字节数组Base64编码
   BASE64Encoder encoder = new BASE64Encoder();
   //返回Base64编码过的字节数组字符串
   return encoder.encode(data);
 }
 /**
  * @Description: base64字符串转化成图片
  * @param:   imgStr
  * @Return:
  */
 public static boolean GenerateImage(String imgStr,String photoname)
 {
   //对字节数组字符串进行Base64解码并生成图片
   //图像数据为空
   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;
       }
     }
     //生成jpeg图片
     String imagePath= Config.getUploadPhysicalPath();
     //System.currentTimeMillis()
     //新生成的图片
     String imgFilePath = imagePath+photoname;
     OutputStream out = new FileOutputStream(imgFilePath);
     out.write(b);
     out.flush();
     out.close();
     return true;
   }
   catch (Exception e)
   {
     return false;
   }
 }
}

来源:https://blog.csdn.net/Curry_BB/article/details/82659661

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com