In my project i'm using a circular image view to display a image that i get from the gallery of the phone and the image is then set to the image view up-to here everything works fine.
But the problem is when i transact from one fragment to other the image gets removed.
So i need a code snippet that helps me to pick a image from the gallery and crop it and then display the image in the image view forever.
PS: this image is also been uploaded to the Fire Base storage. so help me how can i solve this
For image extraction
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK){
Uri imageUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
profileImage.setImageBitmap(bitmap);
}catch (IOException e){
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
for image pick
profileImage = view.findViewById(R.id.profile_image);
profileImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery,"Select Profile Image"), PICK_IMAGE);
}
});
I suggest you use this. it's image cropper https://github.com/ArthurHub/Android-Image-Cropper
for save the bitmap result to sharedPrf you should convert bitmap to base64 and for upload you should convert it to file
example for file
File f = new File(context.getCacheDir(), filename);
f.createNewFile();
//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
for base64:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String base64String = Base64.encodeToString(imageBytes, Base64.NO_WRAP);
To decode the base64 string back to bitmap image:
byte[] decodedByteArray = Base64.decode(base64String, Base64.NO_WRAP);
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedByteArray, 0, decodedString.length);