How to get album art from a song file in android - android

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());

Related

Album art for song is not showing correct in android

Here is my cursor by which I m getting songs from local storage :
cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,MediaStore.Audio.AudioColumns.DURATION+">0", null, sortOrder);
I m displaying album by using another cursor like this shown below because I m not able to do this using same cursor :
ContentResolver musicResolve = getContentResolver();
Uri smusicUri = android.provider.MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor musicCursorTogetAlbum =musicResolve.query(smusicUri,null, null, null, null);
I m displaying album like this but it doesn't display correctly :
musicCursorTogetAlbum.moveToFirst();
musicCursorTogetAlbum.move(cursorPosition);
int x = musicCursorTogetAlbum.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
int id_albumCursor = musicCursorTogetAlbum.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
String thisArt = musicCursorTogetAlbum.getString(x);
Bitmap bm = BitmapFactory.decodeFile(thisArt);
Bitmap bm_temp = BitmapFactory.decodeFile(thisArt);
Drawable dr = new BitmapDrawable(getResources(), bm);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
iv_album_art.setImageBitmap(bm);
}
And cursorPosition is the int type variable which gives position of cursor of cursor which I m using for getting song from local storage.
You can use this method to get album art of songs :
`
public static Bitmap getAlbumart(Context context, Long album_id){
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
try{
final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
if (pfd != null){
FileDescriptor fd = pfd.getFileDescriptor();
bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
pfd = null;
fd = null;
}
} catch(Error ee){}
catch (Exception e) {}
return bm;
}
`

Retrieve images for songs android

I want to retrieve images for all songs in my list but i am getting only one image for all songs. Please tell me where i am wrong.
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = musicResolver.query(musicUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int titleColumn = cursor
.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor
.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
Long albumId = cursor.getLong(cursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
int artistColumn = cursor
.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
do {
Songs song = new Songs();
song.id = cursor.getLong(idColumn);
song.title = cursor.getString(titleColumn);
song.artist = cursor.getString(artistColumn);
Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri,
albumId);
song.imagePath = albumArtUri;
songList.add(song);
} while (cursor.moveToNext());
}
}
I am trying to put it in listview so here is adapter:-
public View getView(int arg0, View arg1, ViewGroup arg2) {
LinearLayout songLay = (LinearLayout)songInf.inflate
(R.layout.cust_list_song, arg2, false);
//get title and artist views
TextView songView = (TextView)songLay.findViewById(R.id.song_title);
TextView artistView = (TextView)songLay.findViewById(R.id.song_artist);
ImageView imageSong = (ImageView) songLay.findViewById(R.id.song_cover);
Songs currSong = songs.get(arg0);
songView.setText(currSong.title);
artistView.setText(currSong.artist);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(
c.getContentResolver(), currSong.imagePath);
bitmap = Bitmap.createScaledBitmap(bitmap, 30, 30, true);
imageSong.setImageBitmap(bitmap);
} catch (FileNotFoundException exception) {
exception.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
songLay.setTag(arg0);
return songLay;
}
I am beginner to this, so need help.
As I can see in your code, that's obvious result since you use the album's image instead of song image
Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri,
albumId);
song.imagePath = albumArtUri;// You set the album art uri as song's image path

Find the size of selected image from gallery in android

I use basic4android and I want to know the size of selected image from gallery.
my code is :
Dim PicChooser As ContentChooser
PicChooser.Initialize("PicChooser")
PicChooser.Show("image/*", "Select a pic")
Sub PicChooser_Result(Success As Boolean, Dir As String, FileName As String)
If Success = True Then
Dim inp As InputStream
inp = File.OpenInput(Dir, FileName)
Dim btm As Bitmap
btm.Initialize2(inp)
end if
end Sub
I use below method in b4a but it doesn't work.
File.Size(Dir,FileName)
it returns zero because Dir and Filename in this sub doesn't really shows the path of the file.
Somewhere i found this maybe untested code:
public static String getContentSizeFromUri(Context context, Uri uri) {
String contentSize = null;
String[] proj = {MediaStore.Images.Media.SIZE };
CursorLoader cursorLoader = new CursorLoader(
context,
uri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null)
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
if (cursor.moveToFirst() )
contentSize = cursor.getString(column_index);
}
return contentSize;
}
Check if return value is null before use.
If you already get the Uri of the file, you can use the following code to get some information
if (uri != null) {
File file = new File(uri.getPath());
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("FileName", file.getName());
jsonObject.put("FilePath", file.getAbsolutePath());
jsonObject.put("FileSize", file.length());
} catch (JSONException e) {
e.printStackTrace();
}
}

How can I display Album Art using MediaStore.Audio.Albums.ALBUM_ART?

I'm trying to build a MP3 player and I want the ImageView to display the album art of respective songs. I've tried the following, but it doesn't work.
albumcover = (ImageView) findViewById(R.id.cover);
String coverPath = songsList.get(songIndex).get(MediaStore.Audio.Albums.ALBUM_ART);
Drawable img = Drawable.createFromPath(coverPath);
albumcover.setImageDrawable(img);
When I try to play the songs, all I get is a blank screen in the ImageView.
Here's how I get album art for a song:
Cursor cursor = getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID+ "=?",
new String[] {String.valueOf(albumId)},
null);
if (cursor.moveToFirst()) {
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
// do whatever you need to do
}
albumId refers to MediaStore.Audio.Media.ALBUM_ID for that song.
If you're are looking for album art for a particular song (rather than in a list of albums), as far as I know it's a two-stage process since ALBUM_ART is a property of MediaStore.Audio.Albums and is not available directly as song metadata.
If you have album ID you get Album Image uri :-
final public static Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(PlayerConstants.sArtworkUri,
listOfAlbums.get(position).getAlbumID());
And if you have a Image uri you can use any of the image loader Glide, Picaso, UIL to display images .
**OR**
you can write your own image loader
public Bitmap getAlbumart(Context context, Long album_id) {
Bitmap albumArtBitMap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
try {
final Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
ParcelFileDescriptor pfd = context.getContentResolver()
.openFileDescriptor(uri, "r");
if (pfd != null) {
FileDescriptor fd = pfd.getFileDescriptor();
albumArtBitMap = BitmapFactory.decodeFileDescriptor(fd, null,
options);
pfd = null;
fd = null;
}
} catch (Error ee) {
} catch (Exception e) {
}
if (null != albumArtBitMap) {
return albumArtBitMap;
}
return getDefaultAlbumArtEfficiently(context.getResources());
}
public Bitmap getDefaultAlbumArtEfficiently(Resources resource) {
if (defaultBitmapArt == null) {
defaultBitmapArt = decodeSampledBitmapFromResource(resource,
R.drawable.default_album_art, UtilFunctions
.getUtilFunctions().dpToPixels(85, resource),
UtilFunctions.getUtilFunctions().dpToPixels(85, resource));
}
return defaultBitmapArt;
}
ContentResolver musicResolve = getContentResolver();
Uri smusicUri = android.provider.MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor music =musicResolve.query(smusicUri,null //should use where clause(_ID==albumid)
,null, null, null);
music.moveToFirst(); //i put only one song in my external storage to keep things simple
int x=music.getColumnIndex(android.provider.MediaStore.Audio.Albums.ALBUM_ART);
String thisArt = music.getString(x);
Bitmap bm= BitmapFactory.decodeFile(thisArt);
ImageView image=(ImageView)findViewById(R.id.image);
image.setImageBitmap(bm);
This method return ArrayList with song path and album art.
public static ArrayList<CommonModel> getAllMusicPathList(Context context) {
ArrayList<CommonModel> musicPathArrList = new ArrayList<>();
Uri songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursorAudio = context.getContentResolver().query(songUri, null, null, null, null);
if (cursorAudio != null && cursorAudio.moveToFirst()) {
Cursor cursorAlbum;
if (cursorAudio != null && cursorAudio.moveToFirst()) {
do {
Long albumId = Long.valueOf(cursorAudio.getString(cursorAudio.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
cursorAlbum = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + "=" + albumId, null, null);
if(cursorAlbum != null && cursorAlbum.moveToFirst()){
String albumCoverPath = cursorAlbum.getString(cursorAlbum.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
String data = cursorAudio.getString(cursorAudio.getColumnIndex(MediaStore.Audio.Media.DATA));
musicPathArrList.add(new CommonModel(data,albumCoverPath ,false));
}
} while (cursorAudio.moveToNext());
}
}
return musicPathArrList;
}
this is CommonModel .
public class CommonModel {
private String path;
private boolean selected;
public String getAlbumCoverPath() {
return albumCoverPath;
}
public void setAlbumCoverPath(String albumCoverPath) {
this.albumCoverPath = albumCoverPath;
}
private String albumCoverPath;
public CommonModel(String path, String albumCoverPath, boolean b) {
this.path = path;
this.albumCoverPath=albumCoverPath;
this.selected=b;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public boolean getSelected() {
return selected;
}
public void setSelected(boolean selected) {
selected = selected;
}
}
You should use Uri.parse("content://media/external/audio/albumart"); to query the albumart. the 1st answer may get exception on some phone (at least mine)
The below code worked for me. I know it has been answered already, it may be useful for someone checking for reference.
public void getAlbumArt() {
try {
ContentResolver cr = getContentResolver();
Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor cursor = cr.query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int albumart = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
do {
String Albumids = cursor.getString(albumart);
Albumid.add(Albumids);
} while (cursor.moveToNext());
}cursor.close();
} catch (NumberFormatException e){
e.printStackTrace();
}
}
public void getSelectedPath(){
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String path= String.valueOf(listView.getItemAtPosition(i));
if(path.equals("null")){
ImageView imgv=(ImageView)view.findViewById(R.id.imageView);
imgv.setImageResource(R.drawable.unknowalbum);
imgv.setMaxHeight(50);
imgv.setMaxWidth(50);
}
else{
Drawable image=Drawable.createFromPath(path);
ImageView imgview=(ImageView)view.findViewById(R.id.imageView);
imgview.setImageDrawable(image);
}
}
});
}
for complete code visit http://vasistaguru.blogspot.com/2017/02/get-albumart-and-trackname-using.html
Example Code
public static Uri getAlbumArtUri(long albumId) {
return ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumId);
}
ArrayList<Uri> albumArtUris = new ArrayList<>();
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{"album_id"}, null, null, null);
cursor.moveToFirst();
do {
long ablumId = cursor.getLong(cursor.getColumnIndexOrThrow("album_id"));
albumArtUris.add(getAlbumArtUri(ablumId));
} while (cursor.moveToNext());

android get real path by Uri.getPath()

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();
}

Categories

Resources