How do I get thumbnail of a video in android - android

I want some help in creating thumbnail of a video being recorded from my android phone and I got this code from this Link, and I modified this part of the code to generate the thumbnail but somehow the thumbnail is not being generated, so any help will be appreciated.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == VIDEO_CAPTURED) {
videoFileUri = data.getData();
if (videoFileUri != null) {
Bitmap image= ThumbnailUtils.createVideoThumbnail(videoFileUri.toString(),MODE_APPEND);
ImageView imageView=(ImageView)findViewById(R.id.image);
imageView.setImageBitmap(image);
}
playVideoButton.setEnabled(true);
}
}

You can use glide. its automatically set thumb image of video.
Glide is also able to display the thumbnail of videos, as long as they're stored on the phone. Let's assume you get the file path by letting the user select a video: Based on this document https://futurestud.io/tutorials/glide-displaying-gifs-and-videos
String filePath = "/storage/emulated/0/Pictures/example_video.mp4";
Glide
.with(context)
.asBitmap()
.load(Uri.fromFile(new File(filePath)))
.into(imageViewGifAsBitmap);

Here is the complete tested working solution:
Try it.
if (videoFileUri != null) {
Bitmap bitmapThumb = null;
try {
bitmapThumb = ThumbnailUtils.createVideoThumbnail(videoFileUri.toString(),
MediaStore.Video.Thumbnails.MINI_KIND);// MINI_KIND, size: 512 x 384 thumbnail | MICRO_KIND, size: 96 x 96 thumbnail
ImageView imageView = (ImageView) findViewById(R.id.image);
// imageView.setImageBitmap(bitmapThumb);
Uri uri = getImageUri(context, bitmapThumb);
Picasso.with(context)
.load(uri)
.placeholder(R.drawable.ic_imagedefault)
.error(R.drawable.ic_imagedefault)
.resize(350, 200)//as per need.
.centerCrop()
.into(imageView);
} catch (Exception e) {
e.printStackTrace();
} finally {
bitmapThumb = null;
}
}
}
Here is the static method for getImageUri :
public static Uri getImageUri(Context inContext, Bitmap inImage) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.PNG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
} catch (Exception e) {
e.printStackTrace();
return Uri.parse("");
}
}

Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Video.Thumbnails.MICRO_KIND);
This works fine for me.
https://developer.android.com/reference/android/media/ThumbnailUtils

Uri uri = getImageUri(context, bitmapThumb);
Glide.with(getContext()).
load(uri).
thumbnail(0.1f).
into(imageView);

Related

ImageView is not showing captured Image using Camera in android

I am trying to choose an image for registration. When clicking the ImageView, the user will be given a choice between taking a picture or choosing from his/her gallery. When the user chooses the gallery option, it will display the selected image. When the user chooses the camera option, the ImageView does not display the image. Below is my code for the OnActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent imgdata) {
super.onActivityResult(requestCode, resultCode, imgdata);
if (requestCode == SELECT_IMAGE && resultCode == RESULT_OK && imgdata != null) {
selectedimage = imgdata.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(selectedimage);
Bitmap yourselectedimage = BitmapFactory.decodeStream(inputStream);
imgchild.setImageBitmap(yourselectedimage);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
}
if (requestCode == CAPTURE_IMAGE && resultCode == RESULT_OK && imgdata != null) {
camImg =(Bitmap) imgdata.getExtras().get("img");
try {
imgchild.setImageBitmap(camImg);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
}
}
The ImageView should display the taken picture from the camera.
I think it should be like this
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
By reading your code, I think it's highly likely that camImg is null because the way you extract bitmap from Intent is incorrect.
Bitmap implements Parcelable, so you need to extract it like this:
camImg = (Bitmap) imgdata.getParcelableExtra("img");
I hope this will work for you.
Set image like this
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
Uri tempUri = getImageUri(getApplicationContext(), photo);
File finalFile = new File(getRealPathFromURI(tempUri));
Log.e("path", finalFile.getAbsolutePath());
To get image path where it is stored
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
I faced same issue with Android Marshmallow, in my case, it is happening due to large bitmap so I figured out with the following code by resizing bitmap
final int maxSize = 960;
int outWidth;
int outHeight;
int inWidth = CameraActivity.bitmap.getWidth();
int inHeight = CameraActivity.bitmap.getHeight();
if(inWidth > inHeight){
outWidth = maxSize;
outHeight = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
iv_captured_image.setImageBitmap(Bitmap.createScaledBitmap(CameraActivity.bitmap, outWidth, outHeight, false));

Capture image from camera return low quality image

I've been developed app to take a picture to be saved in gallery. I've searched online and the easiest way that I could practice was to use data.getExtras().get("data") . So below are the code to take picture from camera. Note that I'm using fragment in this class.
img22a1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CAMERA_01);
}
});
Get the captured image and convert it to string
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_01) {
if (resultCode == Activity.RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream output = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
byte[] byte_arr = output.toByteArray();
((SiteProgress) getActivity().getApplication()).seti22a1(Base64.encodeToString(byte_arr, Base64.DEFAULT));
BitmapDrawable ob = new BitmapDrawable(getResources(), bitmap);
img22a1.setBackgroundDrawable(ob);
} else if (resultCode == Activity.RESULT_CANCELED) {
}
}
}
I save the string into global variable so another activity can access it.
In another activity, I have a button to save the image into folder/gallery by accessing the image string.
for(int i=0;i<=namefile.length;i++){
Bitmap[] bitmap = new Bitmap[namefile.length];
FileOutputStream outputStream = new FileOutputStream(String.valueOf(namefile[i]));
bitmap[i] = BitmapFactory.decodeByteArray(decodedString[i],0,decodedString[i].length);
bitmap[i].compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), namefile[i].getAbsolutePath(), namefile[i].getName(), namefile[i].getName());
}
It worked to save the image into folder/gallery....But the quality of image was very low...I could barely see text in the image.
They said data.getExtras().get("data") supposed to return thumbnail and not the actual image. What I want here is to get the full image and not the thumbnail one.
Any answer will be very appreciated.
From: Android - How to get the image using Intent data
if(data != null)
{
Uri selectedImageUri = data.getData();
filestring = selectedImageUri.getPath();
Bitmap thumbnail = BitmapFactory.decodeFile(filestring, options2);
System.out.println(String.format("Bitmap(CAMERA_IMAGES_REQUEST): %s", thumbnail));
System.out.println(String.format("cap_image(CAMERA_IMAGES_REQUEST): %s", cap_image));
cap_image.setImageBitmap(thumbnail);
}

how to covert image view into bitmap in android studio?

Can anyone tell me how to convert imageview to bitmap? In my app, i'm accessing the gallery and getting a bitmap of a picture into an imageview, then using picasso, i'm resizing the images that are too big to directly uploaded to parse. I can resize the image in the image view using picasso but how do i get the bitmap from the image view to upload to parse? this is my code..
public static final int IMAGE_GALLERY_REQUEST = 20;
private ImageView imgPicture;
public Bitmap image;
public void openGallery(View view){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select Picture"),IMAGE_GALLERY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// if we are here, everything processed successfully.
if (requestCode == IMAGE_GALLERY_REQUEST) {
Uri imageUri = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(imageUri);
image = BitmapFactory.decodeStream(inputStream);
height= image.getHeight();
h= String.valueOf(height);
width= image.getWidth();
w= String.valueOf(width);
if (width>800 || height>600)
{
Picasso.with(this)
.load(imageUri)
.resize(800,600)
.centerCrop()
.into(imgPicture);
// imgPicture.setImageBitmap(image);
//what should i write here to convert this imageview to bitmap? and then later use that bitmap to upload the image to parse?
}
else
{
//do nothing
imgPicture.setImageBitmap(image);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
// show a message to the user indictating that the image is unavailable.
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}
You only can generate the bitmap from imageview but not in real image size, this generate the bitmap with imageview size
Bitmap bitmap;
try {
bitmap = Bitmap.createBitmap(YOUR_VIEW.getWidth(), YOUR_VIEW.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
YOUR_VIEW.draw(canvas);
File root = Environment.getExternalStoragePublicDirectory(Environment.PICTURES);
String fname = "NAME_OF_FILE.jpg";
file = new File(root, fname);
try {
if (!root.exists()) {
root.mkdir();
}
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
YOUR_VIEW.destroyDrawingCache();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
}
If you don't wanna save to a file, use this code:
public static Bitmap getScreenViewBitmap(View v) {
v.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false); // clear drawing cache
return b;
}

ImageView not displaying Image

I am using camera in my app.I need to take picture and should display it in imageview. I am using the following code to take picture from the camera and display it.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(intent, 0);
imageView.setImageURI(capturedImageUri);
This works only for two or sometimes three images,then the imageview doesn't show the image but the image is correctly stored in SD card.
Alternatively i have also used
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
Imageview.setImageBitmap(bitmap);
But i am facing the same problem. can any one help me please.
capturedImageUri will return path to captured Image not the actual Image..
Also, Important Note-- If you dont need a full sized image use-
// cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); Comment this line
Bitmap image = (Bitmap) data.getExtras().get("data");
To get the full sized Bitmap Use following code-
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try
{
// place where to store camera taken picture
tempPhoto = createTemporaryFile("picture", ".png");
tempPhoto.delete();
}
catch(Exception e)
{
return ;
}
mImageUri = Uri.fromFile(tempPhoto);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(cameraIntent, 1);
private File createTemporaryFile(String part, String ext) throws Exception
{
// File to store image temperarily.
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
if(!tempDir.exists())
{
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ContentResolver cr = getApplicationContext().getContentResolver();
try {
cr.notifyChange(mImageUri, null);
File imageFile = new File(tempPhoto.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
Bitmap photo=null;
if (resultCode == 1) {
try {
photo = android.provider.MediaStore.Images.Media.getBitmap(cr, Uri.fromFile(tempPhoto));
imageView.setImageBitmap(photo);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Have you tried putting your setImageUri logic in the activity callback onActivityResult
I think you are trying to supply the image to the imageview before any content is saved to that uri. You need to hook into the callback that gets fired when the camera actually take the picture (i.e. the camera activity finishes and reports its result)
This answer has a full write up
https://stackoverflow.com/a/5991757/418505
possibly something like
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}

How to get Bitmap from an Uri?

How to get a Bitmap object from an Uri (if I succeed to store it in
/data/data/MYFOLDER/myimage.png or file///data/data/MYFOLDER/myimage.png) to use it in my application?
Does anyone have an idea on how to accomplish this?
Here's the correct way of doing it:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
Uri imageUri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
}
}
If you need to load very large images, the following code will load it in in tiles (avoiding large memory allocations):
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(myStream, false);
Bitmap region = decoder.decodeRegion(new Rect(10, 10, 50, 50), null);
See the answer here
Here's the correct way of doing it, keeping tabs on memory usage as well:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
Uri imageUri = data.getData();
Bitmap bitmap = getThumbnail(imageUri);
}
}
public static Bitmap getThumbnail(Uri uri) throws FileNotFoundException, IOException{
InputStream input = this.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither=true;//optional
onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) {
return null;
}
int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;
double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
bitmapOptions.inDither = true; //optional
bitmapOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//
input = this.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
input.close();
return bitmap;
}
private static int getPowerOfTwoForSampleRatio(double ratio){
int k = Integer.highestOneBit((int)Math.floor(ratio));
if(k==0) return 1;
else return k;
}
The getBitmap() call from Mark Ingram's post also calls the decodeStream(), so you don't lose any functionality.
References:
Android: Get thumbnail of image on SD card, given Uri of original image
Handling large Bitmaps
It seems that MediaStore.Images.Media.getBitmap was deprecated in API 29. The recommended way is to use ImageDecoder.createSource which was added in API 28.
Here's how getting the bitmap would be done:
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ImageDecoder.decodeBitmap(ImageDecoder.createSource(requireContext().contentResolver, imageUri))
} else {
MediaStore.Images.Media.getBitmap(requireContext().contentResolver, imageUri)
}
IMPORTANT: ImageDecoder.decodeBitmap read EXIF orientation, Media.getBitmap doesn't
try
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver() , Uri.parse(paths));
}
catch (Exception e)
{
//handle exception
}
and yes path must be in a format of like this
file:///mnt/sdcard/filename.jpg
private void uriToBitmap(Uri selectedFileUri) {
try {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(selectedFileUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This is the easiest solution:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
Uri imgUri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imgUri);
You can retrieve bitmap from uri like this
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
private fun setImage(view: ImageView, uri: Uri) {
val stream = contentResolver.openInputStream(uri)
val bitmap = BitmapFactory.decodeStream(stream)
view.setImageBitmap(bitmap)
}
by using glide library you can get bitmap from uri,
almost in samsung devices image rotated when and we have to check rotation using exifinterface
but using glide no need to check rotation, image always correctly received.
in kotlin you can get bitmap as
CoroutineScope(Dispatchers.IO).launch {
var bitmap = Glide.with(context).asBitmap().load(imageUri).submit().get()//this is synchronous approach
}
I am using this dependency
api 'com.github.bumptech.glide:glide:4.12.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'
Bitmap bitmap = null;
ContentResolver contentResolver = getContentResolver();
try {
if(Build.VERSION.SDK_INT < 28) {
bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri);
} else {
ImageDecoder.Source source = ImageDecoder.createSource(contentResolver, imageUri);
bitmap = ImageDecoder.decodeBitmap(source);
}
} catch (Exception e) {
e.printStackTrace();
}
Inset of getBitmap which is depricated now I use the following approach in Kotlin
PICK_IMAGE_REQUEST ->
data?.data?.let {
val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(it))
imageView.setImageBitmap(bitmap)
}
InputStream imageStream = null;
try {
imageStream = getContext().getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
ContentResolver cr = context.getContentResolver();
try (InputStream input = cr.openInputStream(url)) {
Bitmap bitmap = BitmapFactory.decodeStream(input);
}
Use startActivityForResult metod like below
startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"), PICK_IMAGE);
And you can get result like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case PICK_IMAGE:
Uri imageUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
I have try a lot of ways. this work for me perfectly.
If you choose pictrue from Gallery. You need to be ware of getting Uri from intent.clipdata or intent.data, because one of them may be null in different version.
private fun onChoosePicture(data: Intent?):Bitmap {
data?.let {
var fileUri:Uri? = null
data.clipData?.let {clip->
if(clip.itemCount>0){
fileUri = clip.getItemAt(0).uri
}
}
it.data?.let {uri->
fileUri = uri
}
return MediaStore.Images.Media.getBitmap(this.contentResolver, fileUri )
}
I don't see the right answer, so I'll put this extension here
fun Context.getBitmap(uri: Uri): Bitmap =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) ImageDecoder.decodeBitmap(ImageDecoder.createSource(this.contentResolver, uri))
else MediaStore.Images.Media.getBitmap(this.contentResolver, uri)
Example in code:
val bitmap = context.getBitmap(uri)
Tip: You can also update the extension for activity/fragment, so you don't
need to write the context at all. A little more synth sugar)
you can do this structure:
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
Bundle extras = imageReturnedIntent.getExtras();
bitmap = extras.getParcelable("data");
}
break;
}
by this you can easily convert a uri to bitmap.
hope help u.
(KOTLIN)
So, as of April 7th, 2020 none of the above mentioned options worked, but here's what worked for me:
If you want to store the bitmap in a val and set an imageView with it, use this:
val bitmap = BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }
If you just want to set the bitmap to and imageView, use this:
BitmapFactory.decodeFile(currentPhotoPath).also { bitmap -> imageView.setImageBitmap(bitmap) }
* For getting bitmap from uri. Work for me perfectly.
public static Bitmap decodeUriToBitmap(Context mContext, Uri sendUri) {
Bitmap getBitmap = null;
try {
InputStream image_stream;
try {
image_stream = mContext.getContentResolver().openInputStream(sendUri);
getBitmap = BitmapFactory.decodeStream(image_stream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return getBitmap;
}
val bitmap = context.contentResolver.openInputStream(uri).use { data ->
BitmapFactory.decodeStream(data)
}
You need to open inputstream with
use
as it will automatically close the stream after operation complete.
Full method to get image uri from mobile gallery.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try { //Getting the Bitmap from Gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
rbitmap = getResizedBitmap(bitmap, 250);//Setting the Bitmap to ImageView
serImage = getStringImage(rbitmap);
imageViewUserImage.setImageBitmap(rbitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use coil libray for this purpose on 2022.
https://coil-kt.github.io/coil/compose/
for jetpack compose
AsyncImage(
model = uriOfImage,
contentDescription = null,
)

Categories

Resources