2017-02-04 87 views
1

在我的onCreate方法中,我有一個位圖圖像(從另一個活動傳輸)。將位圖轉換爲base64字符串並保存到共享偏好

Intent intent = getIntent(); 
    Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapClothes"); 

在我的onCreate方法下面,我寫了一個方法將我的位圖轉換爲base64字符串。

public static String encodeToBase64(Bitmap bitmap){ 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    bitmap.compress(Bitmap.CompressFormat.PNG,100,baos); 
    byte[] b = baos.toByteArray(); 
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT); 
    Log.d("Image log:", imageEncoded); 
    return imageEncoded; 
}; 

最後,我的方法在共享偏好保存:

public void savepic (View view){ 
    SharedPreferences mypreference = getSharedPreferences("image", Context.MODE_PRIVATE); 
    String Pic1 = "image1"; 
    SharedPreferences.Editor editor = mypreference.edit(); 
    editor.putString("Pic1",encodeToBase64(bitmap)); 
    editor.commit(); 
}; 

然而,在下面的下面的行,就不能似乎看我的位圖變量(不能解析符號位)。我真的不知道該怎麼辦...任何幫助非常感謝〜

editor.putString("Pic1",encodeToBase64(bitmap)); 
+2

任何特別的原因,你不只是它保存爲圖像文件? –

+0

錯誤的實現。將圖像保存在應用私人文件夾中,並將共享首選項中的圖像路徑存儲。 –

+0

@MikeM。如果我想在本地保存應用程序,我不能保存爲我研究過的圖像文件。 – xlayer

回答

1

我在我的項目中做了同樣的事情。

位圖轉換並存儲到共享偏好

Bitmap photo = (Bitmap) intent.getParcelableExtra("BitmapClothes");      
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    photo.compress(Bitmap.CompressFormat.PNG, 100, baos); 
    byte[] b = baos.toByteArray(); 
    String temp = Base64.encodeToString(b, Base64.DEFAULT); 
    myPrefsEdit.putString("url", temp); 
    myPrefsEdit.commit(); 

從共享優先檢索,並將其加載到一個ImageView的

String temp = myPrefs.getString("url", "defaultString"); 
     try { 
      byte[] encodeByte = Base64.decode(temp, Base64.DEFAULT); 
      Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length); 
      picture.setImageBitmap(bitmap); 
     } catch (Exception e) { 
      e.getMessage(); 
     } 
+0

這是我的問題的完美答案!謝謝! – xlayer

+0

@xlayer永遠樂於幫助... – vishnumm93

相關問題