How to Save a compressed image in shared preference? - android

I have this code that can compress a selected image in the gallery which is very useful when you want to allow the user to add a profile picture. this code works fine but I would like the compressed image to be saved in the shared preferences in order to be persistent.
public void chooseImage(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
public void compressImage(View view) {
if (actualImage == null) {
showError("Please choose an image!");
} else {
// Compress image in main thread using custom Compressor
try {
compressedImage = new Compressor(this)
.setMaxWidth(640)
.setMaxHeight(480)
.setQuality(75)
.setCompressFormat(Bitmap.CompressFormat.WEBP)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFile(actualImage);
setCompressedImage();
} catch (IOException e) {
e.printStackTrace();
showError(e.getMessage());
}
}
}
private void setCompressedImage() {
compressedImageView.setImageBitmap(BitmapFactory.decodeFile(compressedImage.getAbsolutePath()));
compressedSizeTextView.setText(String.format("Size : %s", getReadableFileSize(compressedImage.length())));
Toast.makeText(this, "Compressed image save in " + compressedImage.getPath(), Toast.LENGTH_LONG).show();
Log.d("Compressor", "Compressed image save in " + compressedImage.getPath());
}
private void clearImage() {
actualImageView.setBackgroundColor(getRandomColor());
compressedImageView.setImageDrawable(null);
compressedImageView.setBackgroundColor(getRandomColor());
compressedSizeTextView.setText("Size : -");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
if (data == null) {
showError("Failed to open picture!");
return;
}
try {
actualImage = FileUtil.from(this, data.getData());
actualImageView.setImageBitmap(BitmapFactory.decodeFile(actualImage.getAbsolutePath()));
actualSizeTextView.setText(String.format("Size : %s", getReadableFileSize(actualImage.length())));
clearImage();
} catch (IOException e) {
showError("Failed to read picture data!");
e.printStackTrace();
}
}
}
public void showError(String errorMessage) {
Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
}
private int getRandomColor() {
Random rand = new Random();
return Color.argb(100, rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
}
public String getReadableFileSize(long size) {
if (size <= 0) {
return "0";
}
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
I have looked at all these answers but none deals specifically with the question Que1 Que2 Que3 Que4 Que5
help me how do i record a compressed image

I would not recommend you to do this at all, since you can just save an image to the storage of your phone. However if you really want to do this...
You can convert your image to a byte[] byte array. Then convert it to a Base64 string.
String encodedImg = Base64.encodeToString(bytes, Base64.DEFAULT);
Then store it using:
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", encodedImg);
Then you can use preferences.getString("image", ""); to get the image back. Do a Base64.decode and convert it back to the image.
However, I would recommend you to think about the architecture of your application. Doing this sounds just so wrong.
Maybe this is a better option for you: https://stackoverflow.com/a/17674787/5457878

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;
}
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();
**display your image just anywhere, convert it into a bitmap again **
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}

Related

Get Output Cropped Image URI

I have implemented image cropping in my app using android intent like below:
CropIntent = new Intent("com.android.camera.action.CROP");
I have received the cropped image and displayed on my UI but I want to perform further use cases like upload the cropped image uri. The problem is that no uri is returned in activity.
Here's my crop image intent snippet:
galleryFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Gallery Btn Clicked");
selectFromGallery();
}
});
private void selectFromGallery() {
galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(Intent.createChooser(galleryIntent, "Choose From"), 2);
}
my code in activity result method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
InputStream inputStream;
if (requestCode == 2 && resultCode == RESULT_OK){
if (data != null){
cropImageUri = data.getData();
userImage.setImageURI(cropImageUri);
try {
originalBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), cropImageUri);
inputStream = getContentResolver().openInputStream(data.getData());
originalBitmap = BitmapFactory.decodeStream(inputStream);
Log.d(TAG, "Original bitmap byte count is:\t" + originalBitmap.getByteCount());
resizedBitmap = getResizedBitmap(originalBitmap, 200);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Log.d(TAG, "Resized bitmap byte count is:\t" + resizedBitmap.getByteCount());
try {
File file = saveBitmap("avatar_image");
upLoadFile(file);
} catch (IOException ex) {
ex.printStackTrace();
}
byte[] bytes = stream.toByteArray();
/**
* For Shared Preferences
* **/
encodedImage = Base64.encodeToString(bytes, Base64.DEFAULT);
imagePrefs = getSharedPreferences("ImagePrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = imagePrefs.edit();
editor.putString("image_user", encodedImage).commit();
upLoadBytes(bytes);
} catch (IOException e) {
e.printStackTrace();
}
cropImage();
}
} else if (requestCode == PERM_CODE){
if (data != null){
//I want to get the cropped image uri here but unable to. Have tried converting the bitmap rcvd here to uri but in activity, ntn is returned. kindly guide me
Bundle bundle = data.getExtras();
originalBitmap = bundle.getParcelable("data");
userImage.setImageBitmap(resizedBitmap);
}
}
}
my crop image function:
private void cropImage() {
try {
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(cropImageUri, "image/*");
CropIntent.putExtra("crop", true);
CropIntent.putExtra("outputX", 200);
CropIntent.putExtra("outputY", 200);
CropIntent.putExtra("aspectX", 1);
CropIntent.putExtra("aspectY", 1);
CropIntent.putExtra("scale", true);
CropIntent.putExtra("return-data", true);
startActivityForResult(CropIntent, PERM_CODE);
} catch (ActivityNotFoundException ex){
}
}
Can anyone say how to get the output uri? Thanks.
If the cropped image is showing in an ImageView, follow this link to save it to device storage, then you can upload the file.

how to select multiple images and convert them to base 64?

I am working in application in which I want user to select multiple and convert them to base64, so that I can sent it to server. Is it possibile to select multiple images from gallery and then convert them to base64 and then send it to server
Intent intent = new Intent();
intent.setType("*/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "android.intent.action.SEND_MULTIPLE"), SELECT_PICTURE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == SELECT_PICTURE) {
if (resultCode == RESULT_OK) {
//data.getParcelableArrayExtra(name);
//If Single image selected then it will fetch from Gallery
filePath = data.getData();
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(filePath, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
// text.setText(file_name+",");
img_name.add(file_name);
img_pic.add(getStringImage(bitmap));
// Toast.makeText(this, "1." + file_name, Toast.LENGTH_SHORT).show();
}
} finally {
cursor.close();
}
} else {
String path = data.getData().getPath();
file_name = path.substring(path.lastIndexOf("/") + 1);
// text.setText(file_name);
img_name.add(file_name);
img_pic.add(getStringImage(bitmap));
//Toast.makeText(this, "2." + file_name, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
Sure you can either manage selecting and displaying the images yourself or you can rely on Androids File Intent chooser to let them select and return. You can then use the URIs provided to retrieve the images, convert and send.
Getting user selected images is simple so I won't post that, but just in case it is something you are not familiar with, here is a link that will walk you through it. Select multiple images from android gallery
Now converting to Base64 should be asynctask
Use the following:
public class Base64EncodeMediaAsyncTask extends AsyncTask<Void, Void, MediaModel> {
/*///////////////////////////////////////////////////////////////
// MEMBERS
*////////////////////////////////////////////////////////////////
private static final String TAG = Globals.SEARCH_STRING + Base64EncodeMediaAsyncTask.class.getSimpleName();
private MediaModel mMediaModelToConvert;
/*///////////////////////////////////////////////////////////////
// CONSTRUCTOR
*////////////////////////////////////////////////////////////////
public Base64EncodeMediaAsyncTask(MediaModel model){
mContext = context;
mMediaModelToConvert = model; //it's just a file wrapper, nothing special lol.
}
/*///////////////////////////////////////////////////////////////
// OVERRIDES
*////////////////////////////////////////////////////////////////
#Override
protected MediaModel doInBackground(Void... params) {
try{
InputStream inputStream = new FileInputStream(mMediaModelToConvert.getAbsoluteLocalPath());//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[(int) new File(mMediaModelToConvert.getAbsoluteLocalPath()).length()];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
bytes = output.toByteArray();
mMediaModelToConvert.setBase64String(Base64.encodeToString(bytes, Base64.DEFAULT));
}catch (Exception ex){
A35Log.e(TAG, "Failed to get base 64 encoding for file: " + mMediaModelToConvert.getAbsoluteLocalPath());
return null;
}
return mMediaModelToConvert;
}
#Override
protected void onPostExecute(MediaModel success) {
super.onPostExecute(success);
}
}

Take picture and convert to Base64

I use code below to make a picture with camera. Instead of saving I would like to encode it to Base64 and after that pass it to another API as an input. I can't see method, how to modify code to take pictures in Base64 instead of regular files.
public class CameraDemoActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
}
catch (IOException e)
{
}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
I try to use code below to convert an image to Base64.
public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality)
{
ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
image.compress(compressFormat, quality, byteArrayOS);
return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT);
}
Above described should be a much more direct and easier way than saving image and after that looking for image to encode it.
Try this:
ImageUri to Bitmap:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
String encodedImage = encodeImage(selectedImage);
}
}
Encode Bitmap in base64
private String encodeImage(Bitmap bm)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
return encImage;
}
Encode from FilePath to base64
private String encodeImage(String path)
{
File imagefile = new File(path);
FileInputStream fis = null;
try{
fis = new FileInputStream(imagefile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
//Base64.de
return encImage;
}
output:
I've wrote my code like this :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Camera mCamera = Camera.open();
mCamera.startPreview();// I don't know why I added that,
// but without it doesn't work... :D
mCamera.takePicture(null, null, mPicture);
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
System.out.println("***************");
System.out.println(Base64.encodeToString(data, Base64.DEFAULT));
System.out.println("***************");
}
};
}
It works perfectly...
Just for converting from bitmap to base64 string in kotlin I use:
private fun encodeImage(bm: Bitmap): String? {
val baos = ByteArrayOutputStream()
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
return Base64.encodeToString(b, Base64.DEFAULT)
}
If you want your base64 String to follow the standard format, add this after getting your base64 method from any of the provided answers
String base64 =""; //Your encoded string
base64 = "data:image/"+getMimeType(context,profileUri)+";base64,"+base64;
The method to get imageExtension is
public static String getMimeType(Context context, Uri uri) {
String extension;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
//If scheme is a content
final MimeTypeMap mime = MimeTypeMap.getSingleton();
extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
} else {
//If scheme is a File
//This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
}
return extension;
}
try {
val imageStream: InputStream? = requireActivity().getContentResolver().openInputStream(mProfileUri)
val selectedImage = BitmapFactory.decodeStream(imageStream)
val baos = ByteArrayOutputStream()
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
val encodedString: String = Base64.encodeToString(b,Base64.DEFAULT)
Log.d("check string" ,encodedString.toString())
} catch (e: IOException) {
e.printStackTrace()
}
For kotlin use code is given bellow just copy this and give image uri at "mProfileUri"

Facing Image Uploading and retrieving difficulties to Datastore in android?

I have searched but for some answers but may be my fault couldn't find my desired answer.Now below what i am trying:
I am trying to upload an image like of a status or a post or any profile pic.Profile pic will be small and status or any post image will be big. Now what i want to do:
1. I am converting the image to string text and uploading it to datastore and it's limit is 1Mbyte.So i want to check while uploading image that it doesn't cross limit.
2. I want to check that the image is of png format.If it is not then won't upload.Show a Toast.Can i convert image there?? :(
3. If user is uploading image of suppose 700kbyte but the profile pic is small i.e 100kbyte will be enough for profile pic then i can compress the pic to my defined size and then upload it to datastore.It may remain 700kbyte if it is for status image.
I am converting image to string and uploading it to datastore and again converting back to image while showing it in my app.My code:
public static String imageToStringConverter(Bitmap image){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String imageToString = Base64.encodeToString(byteArray, Base64.NO_WRAP);
return imageToString;
}
public static Bitmap stringToimageConverter(String imageString){
byte[] stringTobyte = Base64.decode(imageString, Base64.NO_WRAP);
Bitmap bmp = BitmapFactory.decodeByteArray(stringTobyte, 0, stringTobyte.length);
return bmp;
}
Now the problem i am facing
:
1.When i am uploading the image it is taking time.So should i use asynctask while uploading after converting the image to my desired size??
2.When i first enter into my app ,i have shown profile pic i.e if i log into my account it will fetch an image for profile from datastore.But it is taking much time and my log in seems to be lengthy.
I have solved my problem by reducing the image.
Here is my code:
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
Uri imageUri;
try {
imageUri = imageReturnedIntent.getData();
}catch(Exception e){
Toast.makeText(getActivity(),"Image Not Found",Toast.LENGTH_SHORT).show();
return;
}
//final InputStream imageStream = getActivity().getContentResolver().openInputStream(imageUri);
//final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
ShrinkBitmapConverter sh = new ShrinkBitmapConverter(getActivity());
Bitmap selectedImage = null;
try {
selectedImage = sh.shrinkBitmap(imageUri,450,350);
} catch (Exception e) {
Toast.makeText(getActivity(),"Image Not Found",Toast.LENGTH_SHORT).show();
}
statusImage = ImageConverter.imageToStringConverter(selectedImage);
if(statusImage.length()>512000){
Toast.makeText(getActivity(),"Image is too big",Toast.LENGTH_LONG).show();
}else {
postImage.setImageBitmap(selectedImage);
}
}
}
ImageConverter.java:
public class ImageConverter {
public static String imageToStringConverter(Bitmap image){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String imageToString = Base64.encodeToString(byteArray, Base64.NO_WRAP);
return imageToString;
}
public static Bitmap stringToimageConverter(String imageString){
byte[] stringTobyte = Base64.decode(imageString, Base64.NO_WRAP);
Bitmap bmp = BitmapFactory.decodeByteArray(stringTobyte, 0, stringTobyte.length);
return bmp;
}
}
ShrinkBitmapConverter.java:
public class ShrinkBitmapConverter {
Context context;
public ShrinkBitmapConverter(Context c){
context=c;
}
public Bitmap shrinkBitmap(Uri uri,int width,int height) throws FileNotFoundException {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = null;;
try {
bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri),null,bmpFactoryOptions);
int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
if (heightRatio > 1 || widthRatio > 1)
{
if (heightRatio > widthRatio)
{
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri),null,bmpFactoryOptions);
} catch (Exception e) {
Toast.makeText(context,"Image Not Found",Toast.LENGTH_SHORT).show();
}
return bitmap;
}
}

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

In my application after login I have to save user name and image in shared preference for other pages. I am able to save name in preference but can't get any where how to save image.
I am trying something like that-
SharedPreferences myPrefrence;
String namePreferance="name";
String imagePreferance="image";
SharedPreferences.Editor editor = myPrefrence.edit();
editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", itemImagePreferance);
editor.commit();
I am trying to save image as string after convert it into object. But when I reconvert it into bitmap I did not get anything.
I solved your problem do something like that:
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;
}
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();
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);
}
Please pass your string inside this method and do what you want.
Finally I solved this problem.
Step:-
1. I wrote some code in onCreate() for get intent data from previous Activity
private Bitmap bitmap;
Intent intent = getIntent();
if (getIntent().getExtras() != null)
{
// for get data from intent
bitmap = intent.getParcelableExtra("PRODUCT_PHOTO");
// for set this picture to imageview
your_imageView.setImageBitmap(bitmap);
sharedPreferences();
}else
{
retrivesharedPreferences();
}
2 create sharedPreferences() and put this code
private void sharedPreferences()
{
SharedPreferences shared = getSharedPreferences("App_settings", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("PRODUCT_PHOTO", encodeTobase64(bitmap));
editor.commit();
}
3 create retrivesharedPreferences() this method and put this code,
private void retrivesharedPreferences()
{
SharedPreferences shared = getSharedPreferences("MyApp_Settings", MODE_PRIVATE);
String photo = shared.getString("PRODUCT_PHOTO", "photo");
assert photo != null;
if(!photo.equals("photo"))
{
byte[] b = Base64.decode(photo, Base64.DEFAULT);
InputStream is = new ByteArrayInputStream(b);
bitmap = BitmapFactory.decodeStream(is);
your_imageview.setImageBitmap(bitmap);
}
}
4 Write encodeTobase64() Method to encode your bitmap into string base64- and put code in this method
public static String encodeTobase64(Bitmap image) {
Bitmap bitmap_image = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap_image.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
return imageEncoded;
}
I hope it will helpful for you.
Encode to Base64?! That's crazy talk! That's way too much information that you are storing to the shared preferences. The strategy you should be doing is saving the Image URI file path, and retrieving it as such. This way, your app won't be storing so much information and become a memory hog when decoding the image.
I made a simple App on Github to demonstrate this idea, if you want to follow:
1. Declare the variables:
private ImageView mImage;
private Uri mImageUri;
2. Select the image:
public void imageSelect() {
Intent intent;
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
}
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE_REQUEST);
}
3. Save the image URI:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_IMAGE_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a image.
// The Intent's data Uri identifies which item was selected.
if (data != null) {
// This is the key line item, URI specifies the name of the data
mImageUri = data.getData();
// Removes Uri Permission so that when you restart the device, it will be allowed to reload.
this.grantUriPermission(this.getPackageName(), mImageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
this.getContentResolver().takePersistableUriPermission(mImageUri, takeFlags);
// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(mImageUri));
editor.commit();
// Sets the ImageView with the Image URI
mImage.setImageURI(mImageUri);
mImage.invalidate();
}
}
}
}
4. Retrieve the image URI when needed:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String mImageUri = preferences.getString("image", null);
mImage.setImageURI(Uri.parse(mImageUri));
That's it! Now we have saved the image uri path to shared preferences cleanly, and have not wasted valuable system resources encoding the image and saving it to SharedPreferences.
//Thanks Maish srivastava
// i will do complete code just copy past and run it sure worked it
//
public class MainActivity extends Activity implements OnClickListener
{
private static int RESULT_LOAD_IMAGE = 1;
public static final String MyPREFERENCES = "MyPre" ;//file name
public static final String key = "nameKey";
SharedPreferences sharedpreferences ;
Bitmap btmap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(key))
{
String u=sharedpreferences.getString(key, "");
btmap=decodeBase64(u);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(btmap);
}
ImageButton imgbtn=(ImageButton) findViewById(R.id.imageButton1);
imgbtn.setOnClickListener(this);
}
public void onClick(View v)
{
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.imageButton1:
try
{ //go to image library and pick the image
Intent i=newIntent(ntent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
catch (Exception e)
{
e.printStackTrace();
}
break;
}
}
#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 cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
btmap=BitmapFactory.decodeFile(picturePath);//decode method called
Editor editor = sharedpreferences.edit();
editor.putString(key, encodeTobase64(btmap));
editor.commit();
}
}
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;
}
public static Bitmap decodeBase64(String input)
{
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Categories

Resources