xlayer
xlayer

Reputation: 25

Converting Bitmap into base64 string and saving in Shared Preference

In my onCreate method, i have a bitmap image (transferred from another activity).

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

Below my onCreate method, i wrote a method to convert my bitmap into base64 string.

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

Finally, my method to save in shared preferences:

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

However, in the following line below, it can't seems to read my bitmap variable (cannot resolve symbol bitmap). i really habe no idea what to do... Any help is greatly appreciated~

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

Upvotes: 2

Views: 778

Answers (1)

Vishnu M Menon
Vishnu M Menon

Reputation: 1469

I have done the same thing in my project.

Bitmap Conversion and Storing into Shared Preference

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

Retrieving from Shared Preference and Loading it into an 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();
        }   

Upvotes: 3

Related Questions