Wednesday, 4 June 2014

how to save image using preferences in android

Bitmap bitmap= BitmapFactory.decodeStream(stream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
byte[] b = baos.toByteArray();

String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
textEncode.setText(encodedImage);

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
edit.commit();

//and then, when retrieving, convert it back into bitmap:

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("image_data", "");

if( !previouslyEncodedImage.equalsIgnoreCase("") ){
    byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
    image.setImageBitmap(bitmap);
}

No comments:

Post a Comment