I am using this code to extract photos(id ,date), but I don't know how can I access to the photo (bitmap) so I can show it!!
//extract photo's informations
public ArrayList<Image> checkGallerieFiles(){
String[] projection = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATE_TAKEN,
MediaStore.Images.Media.DATA
};
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver cr = getActivity().getContentResolver();
Cursor cur = cr.query(uri, projection, "",null, "");
if (cur.moveToFirst()) {
while (cur.moveToNext())
{
Image newImage = new Image ();
newImage.setImageName(cur.getString(cur.getColumnIndex(MediaStore.Images.Media._ID)));
newImage.setImageDate(cur.getString(cur.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN)));
myImageList.add(newImage);
}
}
return (myImageList);
}
This is my code. You get all images I just fetch file path then my second function will give you image bitmap from file path.
private void getallimages(File dir)
{
String[] STAR = { "*" };
controller.images.clear();
final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();//this is my wrapper class
if(new File(imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA))).length()<=10485760)
{
imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));
imageItem.id = id;
imageItem.selection = false; //newly added item will be selected by default this it do for check box unselect u dont need to fill this
controller.images.add(imageItem);//this i just add all info in wrapper class
}
}
}
getbitmap from filepath
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//Drawable d = new BitmapDrawable(getResources(), myBitmap);
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
Related
Hi i'm developer in korea. I have some question so i enter this site.
InputStream is;
URL url =
new URL("http://112.216.25.58:8888/VOD_LAUNCHER/media/youtube_sample3.mp4");
Uri uri = Uri.parse(url.toURI().toString());
is = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
//Bitmap bitmap = BitmapFactory.decodeFile(url.toString());
//MediaMetadataRetriever ret = new MediaMetadataRetriever();
//ret.setDataSource(url.toString());
//Bitmap bitmap = ret.getFrameAtTime(0);
//mImageView.setImageURI(uri);
//Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(uri.toString(), Thumbnails.MICRO_KIND);
mImageView.setImageBitmap(bitmap);
private Bitmap getPreview(URI uri) {
File image = new File(uri);
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
return null;
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
//opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(),
contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I try to use ThumbnailUtil and etc but it didn't work.
How to get ThumbnailImage on android 4.0?
Thanks any reply.
From API level 8 you can just do this:
String path = /*get video path*/;
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MINI_KIND);
Nice and simple :)
If you want to extract a frame of a video you should use this class. The code should be something like that:
MediaMetadataRetriever media = new MediaMetadataRetriever();
media.setDataSource(path);
Bitmap extractedImage = media.getFrameAtTime(time, option);
Hope it´s useful
Try This to get Thumbnail of a Video.
ImageView videoview;
Bitmap thumb = ThumbnailUtils.createVideoThumbnail("YOUR VIDEO STRING PATH", MediaStore.Images.Thumbnails.MINI_KIND);
Matrix matrix = new Matrix();
Bitmap bmThumbnail = Bitmap.createBitmap(thumb, 0, 0,
thumb.getWidth(), thumb.getHeight(), matrix, true);
videoview.setImageBitmap(bmThumbnail);
Edited: Use this method to get string path of Video URI.
/**
* Try to return the absolute file path of the Gallery video.
*
* #param context
* #param uri
* #return the file path or null
*/
public static String getVideoPathFromGallary(final Context context,Uri contentUri) {
String[] proj = { MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DURATION};
Cursor cursor = ((Activity) context).managedQuery(contentUri, proj, null, null, null);
if (cursor == null)
return null;
cursor.moveToFirst();
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
int fileSize = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
long duration = TimeUnit.MILLISECONDS.toSeconds(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)));
System.out.println("size: " + fileSize);
System.out.println("duration: " + duration);
return cursor.getString(column_index);
}
very simple !!! you can use glide library.
first add an imageView on videoView and use the code below:
>
GlideApp.with(getApplicationContext()).load("empty")
.thumbnail(GlideApp.with(getApplicationContext()).load("videoURL"))
.into(imageView);
this code will download an image, and eventually, that leads to less internet consumption.
I know how to get a photo from gallery in android
Intent gallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, PHOTO_REQUEST_CODE);
But how would I specifically select a thumbnail?
REASON FOR BOUNTY:
I have already tried both solutions at Get thumbnail Uri/path of the image stored in sd card + android . They don't work for me. I don't know how to get selectedImageUri, which is of type long, from data in
onActivityResult(int requestCode, int resultCode, Intent data)
String fn = ...; // file name
ContentResolver cr = ctx.getContentResolver();
Cursor c = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{
BaseColumns._ID
}, MediaColumns.DATA + "=?", new String[]{ fn }, null);
if(c!=null) {
try{
if(c.moveToNext()) {
long id = c.getLong(0);
Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MINI_KIND, null);
}
}finally{
c.close();
}
}
If you have its cursor in hand, you can get its ID as ,
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Reffer the following code
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
So, for thumbnail,
Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(cursor, id, MediaStore.Images.Thumbnails.MINI_KIND, null);
Hey so if everything else isn't working for you here is an easy way to make your own thumbnail if you have the Bitmap. If you don't know how to load the Bitmap from the Uri:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
Here is the code to make a nice formatted thumbnail:
final int THUMBNAIL_HEIGHT = 75;//48
final int THUMBNAIL_WIDTH = 75;//66
Float width = new Float(bitmap.getWidth());
Float height = new Float(bitmap.getHeight());
Float ratio = width/height;
bitmap = Bitmap.createScaledBitmap(bitmap, (int)(THUMBNAIL_HEIGHT*ratio), THUMBNAIL_HEIGHT, false);
int padding = (THUMBNAIL_WIDTH - bitmap.getWidth())/2;
image.setPadding(padding, padding, padding, padding);
image.setBackgroundColor(0);
image.setImageBitmap(bitmap);
In this code "image" is the variable for the ImageView. I hope this helps some :D
how to get album art (i.e image file ) from a song file , i am able to get the album art of a file which is in music folder , but how to get ,when the music file is in different path other than music folder
Please any suggestion . Thanks in advance
use this code :)
private Bitmap getAlbumImage(String path) {
android.media.MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(path);
byte[] data = mmr.getEmbeddedPicture();
if (data != null) return BitmapFactory.decodeByteArray(data, 0, data.length);
return null;
}
First get the list of all songs from media store.
public void getSongList() {
// retrieve song info
ContentResolver res = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = res.query(musicUri, null, null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
// get columns
int titleColumn = cursor.getColumnIndex(MediaColumns.TITLE);
int idColumn = cursor.getColumnIndex(BaseColumns._ID);
int artistColumn = cursor.getColumnIndex(AudioColumns.ARTIST);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
// add songs to list
do {
long thisId = cursor.getLong(idColumn);
String pathId = cursor.getString(column_index);
Log.d(this.getClass().getName(), "path id=" + pathId);
metaRetriver.setDataSource(pathId);
try {
art = metaRetriver.getEmbeddedPicture();
Options opt = new Options();
opt.inSampleSize = 2;
songImage = BitmapFactory .decodeByteArray(art, 0, art.length,opt);
}
catch (Exception e)
{ imgAlbumArt.setBackgroundColor(Color.GRAY);
}
String thisTitle = cursor.getString(titleColumn);
String thisArtist = cursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist,songImage));
} while (cursor.moveToNext());
}
Then after getting song list you can use song.getsongImage();
Bitmap bm= BitmapFactory.decodeFile(song.getsongImage());
ImageView image=(ImageView)findViewById(song.getsongImage());
Currently developing an app which loads images from SD card. In the emulator the following works fine and finds images to display. However, on the Galaxy S2 and S3 - no images are ever displayed. Any ideas?
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
{ MediaStore.Images.Thumbnails._ID },
null,
null,
MediaStore.Images.Media._ID
);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int size = cursor.getCount();
int imageId = 0;
for (int i = 0; i < size; i++) {
if(cursor.isClosed()) {
continue;
}
cursor.moveToPosition(i);
imageId = cursor.getInt(columnIndex);
uri = Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
Integer.toString(imageId)
);
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(newBitmap);
}
}
} catch (IOException e) {}
}
cursor.close();
return null;
After testing on device found the following resolved the issue:
BitmapFactory.Options options = new BitmapFactory.Options();
options.outHeight = 70;
options.outWidth = 70;
Bitmap bitmap = null;
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
PROJECTION,
null,
null,
MediaStore.Images.Media._ID
);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int size = cursor.getCount();
for (int i = 0; i < size; i++) {
if(cursor.isClosed()) {
break;
}
cursor.moveToPosition(i);
bitmap = MediaStore.Images.Thumbnails.getThumbnail(
getContentResolver(),
cursor.getInt(columnIndex),
MediaStore.Images.Thumbnails.MICRO_KIND,
options
);
publishProgress(new LoadedImage(bitmap));
}
cursor.close();
I'm trying to get image from gallery.
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select picture"), resultCode );
After I returned from this activity I have a data, which contains Uri. It looks like:
content://media/external/images/1
How can I convert this path to real one (just like '/sdcard/image.png') ?
Thanks
This is what I do:
Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));
and:
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
NOTE: managedQuery() method is deprecated, so I am not using it.
Last edit: Improvement. We should close cursor!!
Is it really necessary for you to get a physical path?
For example, ImageView.setImageURI() and ContentResolver.openInputStream() allow you to access the contents of a file without knowing its real path.
#Rene Juuse - above in comments... Thanks for this link !
.
the code to get the real path is a bit different from one SDK to another so below we have three methods that deals with different SDKs.
getRealPathFromURI_API19(): returns real path for API 19 (or above but not tested)
getRealPathFromURI_API11to18(): returns real path for API 11 to API 18
getRealPathFromURI_below11(): returns real path for API below 11
public class RealPathUtil {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
font: http://hmkcode.com/android-display-selected-image-and-its-real-path/
UPDATE 2016 March
To fix all problems with path of images i try create a custom gallery as facebook and other apps. This is because you can use just local files ( real files, not virtual or temporary) , i solve all problems with this library.
https://github.com/nohana/Laevatein (this library is to take photo from camera or choose from galery , if you choose from gallery he have a drawer with albums and just show local files)
Note This is an improvement in #user3516549 answer and I have check it on Moto G3 with Android 6.0.1
I have this issue so I have tried answer of #user3516549 but in some cases it was not working properly.
I have found that in Android 6.0(or above) when we start gallery image pick intent then a screen will open that shows recent images when user select image from this list we will get uri as
content://com.android.providers.media.documents/document/image%3A52530
while if user select gallery from sliding drawer instead of recent then we will get uri as
content://media/external/images/media/52530
So I have handle it in getRealPathFromURI_API19()
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
if (uri.getHost().contains("com.android.providers.media")) {
// Image pick from recent
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
} else {
// image pick from gallery
return getRealPathFromURI_BelowAPI11(context,uri)
}
}
EDIT1 : if you are trying to get image path of file in external sdcard in higher version then check my question
EDIT2 Here is complete code with handling virtual files and host other than com.android.providers I have tested this method with content://com.adobe.scan.android.documents/document/
EDIT:
Use this Solution here: https://stackoverflow.com/a/20559175/2033223
Works perfect!
First of, thank for your solution #luizfelipetx
I changed your solution a little bit. This works for me:
public static String getRealPathFromDocumentUri(Context context, Uri uri){
String filePath = "";
Pattern p = Pattern.compile("(\\d+)$");
Matcher m = p.matcher(uri.toString());
if (!m.find()) {
Log.e(ImageConverter.class.getSimpleName(), "ID for requested image not found: " + uri.toString());
return filePath;
}
String imgId = m.group();
String[] column = { MediaStore.Images.Media.DATA };
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ imgId }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
Note: So we got documents and image, depending, if the image comes from 'recents', 'gallery' or what ever. So I extract the image ID first before looking it up.
One easy and best method copy file to the real path and then get their path I checked it 10 devices on android API-16 to API-30 working fine.
#Nullable
public static String createCopyAndReturnRealPath(
#NonNull Context context, #NonNull Uri uri) {
final ContentResolver contentResolver = context.getContentResolver();
if (contentResolver == null)
return null;
// Create file path inside app's data dir
String filePath = context.getApplicationInfo().dataDir + File.separator + "temp_file";
File file = new File(filePath);
try {
InputStream inputStream = contentResolver.openInputStream(uri);
if (inputStream == null)
return null;
OutputStream outputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0)
outputStream.write(buf, 0, len);
outputStream.close();
inputStream.close();
} catch (IOException ignore) {
return null;
}
return file.getAbsolutePath();
}
Hii here is my complete code for taking image from camera or galeery
//My variable declaration
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_REQUEST = 1;
Bitmap bitmap;
Uri uri;
Intent picIntent = null;
//Onclick
if (v.getId()==R.id.image_id){
startDilog();
}
//method body
private void startDilog() {
AlertDialog.Builder myAlertDilog = new AlertDialog.Builder(yourActivity.this);
myAlertDilog.setTitle("Upload picture option..");
myAlertDilog.setMessage("Where to upload picture????");
myAlertDilog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
picIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
picIntent.setType("image/*");
picIntent.putExtra("return_data",true);
startActivityForResult(picIntent,GALLERY_REQUEST);
}
});
myAlertDilog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(picIntent,CAMERA_REQUEST);
}
});
myAlertDilog.show();
}
//And rest of things
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==GALLERY_REQUEST){
if (resultCode==RESULT_OK){
if (data!=null) {
uri = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
options.inSampleSize = calculateInSampleSize(options, 100, 100);
options.inJustDecodeBounds = false;
Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
imageofpic.setImageBitmap(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}else if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("data")) {
bitmap = (Bitmap) data.getExtras().get("data");
uri = getImageUri(YourActivity.this,bitmap);
File finalFile = new File(getRealPathFromUri(uri));
imageofpic.setImageBitmap(bitmap);
} else if (data.getExtras() == null) {
Toast.makeText(getApplicationContext(),
"No extras to retrieve!", Toast.LENGTH_SHORT)
.show();
BitmapDrawable thumbnail = new BitmapDrawable(
getResources(), data.getData().getPath());
pet_pic.setImageDrawable(thumbnail);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
private String getRealPathFromUri(Uri tempUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = this.getContentResolver().query(tempUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private Uri getImageUri(YourActivity youractivity, Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String path = MediaStore.Images.Media.insertImage(youractivity.getContentResolver(), bitmap, "Title", null);
return Uri.parse(path);
}
This helped me to get uri from Gallery and convert to a file for Multipart upload
File file = FileUtils.getFile(this, fileUri);
https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
This code work for me in android 11 and 12
private static String getRealPathFromURI(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getFilesDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return file.getPath();
}