1. 程式人生 > >Java圖片Base64編碼

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());
   //##########################################################//