将位图转换为 base64 字符串并保存在共享首选项中

Converting Bitmap into base64 string and saving in Shared Preference

在我的 onCreate 方法中,我有一个位图图像(从另一个 activity 传输)。

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));

我在我的项目中做过同样的事情。

位图转换并存储到共享首选项

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();
        }