将图片文件流转换成base64字符串

时间:2022-11-12 23:37:24

/**
  * 将文件流转换成base64字符串
  * @param screenshot    文件流
  * @return
  */
 private String file2ImgStr(File screenshot){
  try {
   byte[] data = null;
   // 读取图片字节数组
   try {
    //得到输入流
    InputStream in = new FileInputStream(screenshot);
    data = new byte[in.available()];
    in.read(data);
    in.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
   // 对字节数组Base64编码
   BASE64Encoder encoder = new BASE64Encoder();
   return encoder.encode(data);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

public static File byteArrayToFile(String path, String FileName, Object byteArr){
  File directory = new File(path);
  //不是文件夹,就返回空
  if(!directory.isDirectory() || null == byteArr)return null;
  if(!directory.exists()){
   directory.mkdirs();
  }
  //文件
  File file = new File(path,FileName);
  if(!file.exists()){
   try {
    file.createNewFile();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  FileOutputStream out = null;
  InputStream in = null;
  try {
   out = new FileOutputStream(file);
   out.write((byte[])byteArr);
   out.flush();
  } catch (Exception e) {
   Blob b = (Blob)byteArr;
   try {
    in = b.getBinaryStream();
    int len = 1024*8;
    int offset = 0;
    byte[] buf = new byte[len];
    while((offset=in.read(buf, 0, len))!=-1){
     out.write(buf, 0, offset);
    }
    out.flush();
   } catch (Exception e1) {
    e1.printStackTrace();
   }
  }finally{
   if(null != out){
    try {
     out.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if(null != in){
    try {
     in.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return file;
 }

 

/**
  * 将File文件转换为byte数组
  * @param f  file文件
  * @return   字节数组
  */
 @SuppressWarnings("resource")
 public static byte[] FileToByteArray(File f){
  int len = 1024*8;
  byte[] buf = new byte[len];
  int offset = 0;
  FileInputStream in = null;
  ByteArrayOutputStream out = null;
  try {
   in = new FileInputStream(f);
   out = new ByteArrayOutputStream();
   while((offset=in.read(buf, 0, len))!=-1){
    out.write(buf, 0, offset);
   }
   return out.toByteArray();
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   if(null != in){
    try {
     in.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
   if(null != out){
    try {
     out.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return null;
 }

public static void main(String[] args){

//将附件内容转换成流
  File f = (File)byteArrayToFile(保存图片的路径, “图片字符串” ,utf003);
  //将流转换为base64字符串
  String strBase64 = file2ImgStr(f);
  //获取图片流
  BufferedImage src = javax.imageio.ImageIO.read(new FileInputStream(f));

}