2016-06-22 70 views
0

我正在開發Android應用程序。在我的應用程序中,我正在使用位圖。我正在做的是我將位圖轉換爲字節數組。然後我將字節數組轉換爲字符串。我需要做一些理由。將位圖轉換爲字節數組正在工作。字節數組到字符串也被轉換。然後問題開始,當我使用該轉換的字符串。我將該字符串轉換回字節數組。然後我將該字節數組轉換回位圖。但是位圖總是空的。請參閱下面的代碼。將位圖轉換爲bytearray轉換爲字符串然後轉換回位圖在Android中始終爲空

這是我的功能轉換位爲字節數組

public static byte[] ConvertBitmapToByteArray(Bitmap bitmap) 
    { 
     if(bitmap==null) 
     { 
      return null; 
     } 
     else{ 
      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); 
      byte[] byteArray = stream.toByteArray(); 

      return byteArray; 
     } 
} 

這是一種將字節數組轉換爲位圖功能

public static Bitmap ConvertByteArarysToBitmap(byte[] byteArray) 
    { 
     if(byteArray!=null) 
     { 
      return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); 
     } 
     else{ 
      return null; 
     } 
} 

這些都是我轉換

byte[] byteArray = Helper.ConvertBitmapToByteArray(Bitmap bitmap); 
//convert byte array to string 
String imageString = new String(byteArray,"UTF-8"); 
//I convert that string back to byte array 
byte[] reconvertedByteArray = imageString.getBytes("UTF-8"); 
Bitmap reconvertedBitmap = Helper.ConvertByteArarysToBitmap(reconvertedByteArray); 
步驟

在我的代碼中,最後一次reconvertedBitmap始終爲空。我的代碼有什麼問題?將字節數組轉換爲字符串並將該字符串轉換回字節數組的正確方法是什麼?我的代碼中缺少什麼?

+0

如果你需要得到字節轉換成字符串,用base64編碼。 https://developer.android.com/reference/android/util/Base64.html – dharms

+0

它的工作原理。感謝您的支持。 –

+0

你可以上傳答案嗎?我想加入它。 –

回答

2

要正確地將byte[]轉換爲String,應該使用Base64.encodeToString()

Documentation

相關問題