How to Store Images Using Sharedpreference in Android

How to store images using SharedPreference in android?

Its not recommended to store image in Share preferences And you should store that image to sdcard.And then store image path (from sdcard) into Share preferences like this--

    SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit=shre.edit();
edit.putString("imagepath","/sdcard/imh.jpeg");
edit.commit();

and then fetch image from sdcard by using this path

How to store an image using sharedpreferences? Android

If you want to use sharedPreferences, use the below code:

  SharedPreferences sharedPreferences;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("data", context.MODE_PRIVATE);

//Adding the picture bit

imgButton = (ImageButton) findViewById(R.id.AddPic);
imgButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent GaleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(GaleryIntent, RESULT_LOAD_IMAGE);
}
});

if(sharedPreferences!=null)
String path = sharedPreferences.getString("path", null);
if(path!=null)
imgButton.setImageBitmap(BitmapFactory.decodeFile(path));

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri SelectedImage = data.getData();
String[] FilePathColumn = {MediaStore.Images.Media.DATA };

Cursor SelectedCursor = getContentResolver().query(SelectedImage, FilePathColumn, null, null, null);
SelectedCursor.moveToFirst();

int columnIndex = SelectedCursor.getColumnIndex(FilePathColumn[0]);
String picturePath = SelectedCursor.getString(columnIndex);
SelectedCursor.close();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("path", picturePath);
editor.commit();

// Drawable d = new BitmapDrawable(getResources(),BitmapFactory.decodeFile(picturePath));
// btnOpenGalery .setImageBitmap(d);
imgButton.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Toast.makeText(getApplicationContext(), picturePath, Toast.LENGTH_SHORT).show();

}

}

How to save Image in shared preference in Android | Shared preference issue in Android with Image

I solved your problem do something like that:

  1. Write Method to encode your bitmap into string base64-

    // method for bitmap to base64
    public static String encodeTobase64(Bitmap image) {
    Bitmap immage = image;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

    Log.d("Image Log:", imageEncoded);
    return imageEncoded;
    }
  2. Pass your bitmap inside this method like something in your preference:

    SharedPreferences.Editor editor = myPrefrence.edit();
    editor.putString("namePreferance", itemNAme);
    editor.putString("imagePreferance", encodeTobase64(yourbitmap));
    editor.commit();
  3. And when you want to display your image just anywhere, convert it into a bitmap again using the decode method:

    // method for base64 to bitmap
    public static Bitmap decodeBase64(String input) {
    byte[] decodedByte = Base64.decode(input, 0);
    return BitmapFactory
    .decodeByteArray(decodedByte, 0, decodedByte.length);
    }
  4. Please pass your string inside this method and do what you want.

How to Save images to ImageView using Shared Preferences

Write Method to encode your Bitmap into string base64

public static String encodeToBase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

Log.d("Image Log:", imageEncoded);
return imageEncoded;
}

Pass yourBitmap inside this method like something encodeTobase64 in your preference

        SharedPreferences myPrefrence = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefrence.edit();
editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", encodeToBase64(yourBitmap));
editor.commit();

And when you want any where display your image just convert it into Bitmap again using decodeToBase64 method

public static Bitmap decodeToBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}

here is code to get Bitmap again

SharedPreferences myPrefrence = getPreferences(MODE_PRIVATE);
String imageS = myPrefrence.getString("imagePreferance", "");
Bitmap imageB;
if(!imageS.equals("")) imageB = decodeToBase64(imageS);

But in my opinion you should keep inside shared preference only path to bitmap.

How to store an image path in the shared preferences in android?

All you have to do is, convert your image to it's Base64 string representation:

Bitmap realImage = BitmapFactory.decodeStream(stream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.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);
imageConvertResult.setImageBitmap(bitmap);
}

However, I have to tell you that Base64 support is only recently included in API8. To target on lower API version, you need to add it first. Luckily, this guy already have the needed tutorial.

Also i have to tell you that this is a complex procedure and shareprefrence use only to store small amount of data such as user name and password that's way you can also use such a method:

store image path (from sdcard) into Share preferences like this--

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit=shre.edit();
edit.putString("imagepath","/sdcard/imh.jpeg");
edit.commit();

To load your image path you can use this

final SharedPreferences sharedPreference = getSharedPreferences(
"pref_key", MODE_PRIVATE);
if (sharedPreference.contains("imagepath")) {
String mFilePath = sharedPreference.getString(imagepath,
null);
}

After getting you path you can use:

File imgFile = new  File(mFilePath);
if(imgFile.exists()){

Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);

}

how to save imageview to sharedpreference using kotlin?

First of all, if you are new to Android Development, please check Picasso for uploading images.
In short, it makes it easier/faster to upload images using resource id/url.

Your question really depends on the type of images you want user to select in the future.

1) If all of the images that can be selected are already in the application you can just save the resource id of image in SharedPreferences as an int

val sharedPref: SharedPreferences = context.getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE)

// Resource id is the int under drawables folder ->R.drawable.myImage
fun save(KEY_NAME: String, value: Int) {
val editor: SharedPreferences.Editor = sharedPref.edit()

editor.putInt(KEY_NAME, value)

editor.apply()
}
fun getInt(KEY_NAME: String): Int {

return sharedPref.getInt(KEY_NAME, 0)
}

2) If you are letting user to select from gallery (this is the tricky part) inside onActivityResult(which gets called after user selects an image with the argument, Intent data, that includes the information on image). Accessing the data of intent (data.getData()) will give you the URI. Then you need to find the path of the image (path where the image is stored in user's phone) and save it to SharedPreferences. I will leave getting the path of image as a challenge to you. And when you want to upload the image you can just;

  Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
myLayoutItem.setBackground(drawable);

3) If you have a server you can just upload your images there and store the url as a string in SharedPreferences/associate url with an image attribute of user. And use Picasso to display the image.

How to store and retrieve bitmap in sharedPreferences in Android?

Hey friends I got the solution of my problem here I post my code so that others can use this solution..

1). on button click - open camera for captureing image

ContentValues values = new ContentValues();  
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST);

2). on button cllick - open Gallery for select image

Intent galleryintent = new Intent(Intent.ACTION_GET_CONTENT);
galleryintent.setType("image/*");
startActivityForResult(galleryintent, IMAGE_PICK);

3). Static variables

private static final int CAMERA_REQUEST = 0; 
private static final int IMAGE_PICK = 1;

4). onActivityResult

    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
switch(requestCode)
{
case CAMERA_REQUEST:
if(resultCode == RESULT_OK)
{
String[] projection = { MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor.getString(column_index_data);
Log.d("photos*******"," in camera take int "+capturedImageFilePath);

Bitmap photo_camera = BitmapFactory.decodeFile(capturedImageFilePath, options);

if(data != null)
{
img_1.setImageBitmap(photo_camera);
prefsEditor.putString(Global.PHOTO_1,capturedImageFilePath);
}
}
case IMAGE_PICK:
if(resultCode == RESULT_OK)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};

Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();

// Bitmap photo = BitmapFactory.decodeFile(filePath);
Bitmap photo_gallery = BitmapFactory.decodeFile(filePath,options);
img_1.setImageBitmap(photo_gallery);
prefsEditor.putString(Global.PHOTO_1, filePath);
}

}
prefsEditor.commit();
}

5). in onDestroy()
You have to destroy all bitmap which you setted.

@Override
public void onDestroy()
{
super.onDestroy();
if(photo_camera != null)
{
photo_camera.recycle();
}
if(photo_gallery != null)
{
photo_gallery.recycle();
}
}

6). At the time when you fetch data from sharedPrefrences you have to convert string in to Bitmap and then you can set bitmap in ImageView.
for example, Bitmap bit1 = BitmapFactory.decodeFile(strimg1);
and then set , imageView.setImageBitmap



Related Topics



Leave a reply



Submit