2016-04-08 115 views
7

它可能是重複的,但我面臨一些問題將圖像轉換爲Base64發送它爲Http Post。我試過這段代碼,但它給了我錯誤的編碼字符串。如何將圖像轉換爲java中的base64字符串?

public static void main(String[] args) { 

      File f = new File("C:/Users/SETU BASAK/Desktop/a.jpg"); 
      String encodstring = encodeFileToBase64Binary(f); 
      System.out.println(encodstring); 
     } 

     private static String encodeFileToBase64Binary(File file){ 
      String encodedfile = null; 
      try { 
       FileInputStream fileInputStreamReader = new FileInputStream(file); 
       byte[] bytes = new byte[(int)file.length()]; 
       fileInputStreamReader.read(bytes); 
       encodedfile = Base64.encodeBase64(bytes).toString(); 
      } catch (FileNotFoundException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      return encodedfile; 
     } 

輸出: [B @ 677327b6

但我在網上很多編碼器轉換這個相同的圖像爲Base64,他們都給出了正確的Base64大串。

編輯:它是如何重複?這是我的重複的鏈接不給我轉換字符串我想要的解決方案。

我在這裏丟失了什麼?

+0

你是如何確定這是不正確的基地64字符串? –

+0

因爲在線編碼器正在返回base64的大字符串 –

+0

您可以提供POST方法的代碼嗎?我在同一個問題(張貼圖像...)謝謝! – Yekatandilburg

回答

15

的問題是,你回電話的toString()Base64.encodeBase64(bytes)它返回一個字節數組。所以你最終得到的是一個字節數組的默認字符串表示,它對應於你得到的輸出。

相反,你應該做的:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8"); 
+0

解決了我的問題 –

+2

String strBase64 = Base64.encodeToString(byteArray, 0) –

0

這是爲我做的。您可以將輸出格式的選項更改爲Base64.Default。

// encode base64 from image 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); 
byte[] b = baos.toByteArray(); 
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP); 
+0

在哪裏餵我的圖像文件?這裏是 –

+0

,它被加載到imageBitmap中。方法.compress轉換並編碼成baos – MojioMS

+0

Base64.URL_SAFE這些不適合我?什麼是導入? –

4

我想你可能想:

String encodedFile = Base64.getEncoder().encodeToString(bytes); 
+0

import org.apache.commons.codec.binary.Base64;我正在導入這個..這裏Base64沒有getEncoder()像東西 –

+0

@setubasak它是關於'java.util.Base64'在Java 8中添加的。 – Pshemo

相關問題