Java图片Base64编码

//##########################################################//
   String uploadDir = com.bstek.dorado.core.Configure.getString(
     Constants.file_upload_config_path);
   String filePath = uploadDir + "/" + emp.getPhoto();
   //判断文件是否存在
   File file = new File(filePath);
   if(!file.exists()){
    System.out.println("文件不存在," + filePath);
    return "文件不存在" + filePath;
   }
   //读文件
   BufferedInputStream bufferedInput = null;
   byte[] buffer = new byte[1024*1024];
   int bytesReadTotal = 0;
   try {
    //创建BufferedInputStream 对象
    bufferedInput = new BufferedInputStream(new FileInputStream(filePath));
    int bytesRead = 0;
    //从文件中按字节读取内容,到文件尾部时read方法将返回-1
    while ((bytesRead = bufferedInput.read(buffer)) != -1) {
     bytesReadTotal += bytesRead;
    }
   } catch (Exception ex) {
    ex.printStackTrace();
   } finally {
    //关闭 BufferedInputStream
    try {
     if (bufferedInput != null){
      bufferedInput.close();
     }
    } catch (IOException ex) {
     ex.printStackTrace();
    }
   }
   //System.out.println("读文件成功,Size:" + bytesReadTotal);
   
   //数组复制(BASE64编码 不能自动控制长度)
   byte[] buffer2 = new byte[bytesReadTotal];
   System.arraycopy(buffer, 0, buffer2, 0, bytesReadTotal);
   
   //编码
   BASE64Encoder base64En = new BASE64Encoder();
   String fileStr = base64En.encode(buffer2);
   //System.out.println("编码成功,Size:" + fileStr.length());
   //##########################################################//

猜你喜欢

转载自blog.csdn.net/tanzongbiao/article/details/82528689