Android:
I am using following code to insert image into album
According to description this method insert image also creates its thumbnail i don't want thumbnail to be created how can i stop thumbnail creation ?
Problem is I write image in album but when i select image from album it returns the thumbnail image path which is not required.
insert image parameters
Parameters
scr The content resolver to use
source The stream to use for the image
title The name of the image
description The description of the image
MediaStore.Images.Media.insertImage(contentResolver ,file.getAbsolutePath(),
file.getName(), );
I struggled with this as well. To get the actual image data location using the images resource URI:
String dataColumnName = MediaStore.Images.Media.DATA;
Uri mediaUri = //Image's URI;
if (mediaUri != null)
{
String[] proj = { dataColumnName };
Cursor actualimagecursor = managedQuery(mediaUri, proj, null, null, null);
int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(dataColumnName);
boolean hasValues = actualimagecursor.moveToFirst();
if (hasValues)
{
//this is the file location of the image
String path = actualimagecursor.getString(actual_image_column_index);
}
}
Related
I've been attempting to look for a solution with regards to the problem as stated in the title above but to no avail.
I'm trying to find a way to check if an Audio file has or does not have an album art, so in the case when there is no album art, I'll be able to set my own drawable for it.
Here's the code I'm running to initialize my song list.
ContentResolver cr = getActivity().getContentResolver();
Uri songsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String songsSelection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
String songsSortOrder = MediaStore.Audio.Media.TITLE + " ASC";
Cursor songCur = cr.query(songsUri, null, songsSelection, null, songsSortOrder);
int songCount = 0;
if(songCur != null)
{
songCount = songCur.getCount();
if(songCount > 0)
{
while(songCur.moveToNext())
{
//String data = songCur.getString(songCur.getColumnIndex(MediaStore.Audio.Media.DATA));
// Debug
//Log.e("Song Path", data);
// (long _id, long _albumId, long _artistId, String _title,
// String _artistName, String _albumName, int _duration)
//Log.e("Music ID", songCur.getString(cur.getColumnIndex(MediaStore.Audio.Media._ID)));
//Log.e("Music Album ID", songCur.getString(songCur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
//Log.e("Music Artist ID", songCur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)));
//Log.e("Music Title", songCur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)));
//Log.e("Music Artist Name", songCur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
//Log.e("Music Album Name", songCur.getString(songCur.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
//Log.e("Music Duration", songCur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)));
mediaManager.songFiles.add(new Song(
songCur.getString(songCur.getColumnIndex(MediaStore.Audio.Media.DATA)),
songCur.getLong(songCur.getColumnIndex(MediaStore.Audio.Media._ID)),
songCur.getLong(songCur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)),
songCur.getLong(songCur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)),
songCur.getString(songCur.getColumnIndex(MediaStore.Audio.Media.TITLE)),
songCur.getString(songCur.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
songCur.getString(songCur.getColumnIndex(MediaStore.Audio.Media.ALBUM)),
songCur.getInt(songCur.getColumnIndex(MediaStore.Audio.Media.DURATION))));
}
}
songCur.close();
}
Let me know if you require any further explanation on my question.
I noticed in your code that you're getting retrieving the album_id of a particular song so a while back I discovered a simple way to fetch album art by appending the album_id to a particular URI, checkout the following code
public Uri getAlbumArtUri(long albumID) {
return ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumID);
}
I then use an Image Loading library like Universal Image Loader or Glide to load the image into an ImageView, like so:
ImageLoader.getInstance().displayImage
(getAlbumArtUri(song.albumId).toString(),
holder.albumArt, new DisplayImageOptions.Builder().cacheInMemory(true).
showImageOnFail(R.drawable.albumart_mp_unknown).resetViewBeforeLoading(true).
build());
showImageOnFail() takes in a drawable that would be displayed incase of error.(This means the song doesn't have album artwork)
P.S I also found the solution discussed on this Stack Overflow Post Quite useful:
Most robust way to fetch Album Art in Android
Hope this helps!
I am trying to load images and show them as a gallery in the form of list.
The problem is that I am able to do it from default android gallery, but I don't know how to do t for custom folder. for e.g /Pictures folder. I have been trying, here is the code that I use for default gallery, I want it for some other folder, e.g /Pictures/Col.
public static List<PhotoItem> getAlbumThumbnails(Context context){
final String[] projection = {MediaStore.Images.Thumbnails.DATA, MediaStore.Images.Thumbnails.IMAGE_ID};
Cursor thumbnailsCursor = context.getContentResolver().query( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
// Extract the proper column thumbnails
int thumbnailColumnIndex = thumbnailsCursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA);
ArrayList<PhotoItem> result = new ArrayList<PhotoItem>(thumbnailsCursor.getCount());
if (thumbnailsCursor.moveToFirst()) {
do {
// Generate a tiny thumbnail version.
int thumbnailImageID = thumbnailsCursor.getInt(thumbnailColumnIndex);
String thumbnailPath = thumbnailsCursor.getString(thumbnailImageID);
Uri thumbnailUri = Uri.parse(thumbnailPath);
Uri fullImageUri = uriToFullImage(thumbnailsCursor,context);
// Create the list item.
PhotoItem newItem = new PhotoItem(thumbnailUri,fullImageUri);
result.add(newItem);
} while (thumbnailsCursor.moveToNext());
}
thumbnailsCursor.close();
return result;
}
What all should I change here, I tried to change projection, query parameters but failed, new in this field, please help :)
You can custom recent-images library for your purpose. It's very simple and easy to use library.
I m just trying to get image description from image uri
I already got the image (Bitmap) with this uri but I can't get the description of it
Its a pretty simple question. I hope you guys can help me :)
by "image description" I talking about what I wrote with this function: insertImage(ContentResolver cr, String imagePath, String name, String description) (last arguement is what I want to get again (once its saved))
this is how I did:
String[] projection = {MediaStore.Images.Media.DESCRIPTION};
Cursor c = MediaStore.Images.Media.query(getContentResolver(),intent.getData(),projection);
c.moveToFirst();
String description = c.getString(c.getColumnIndex(MediaStore.Images.Media.DESCRIPTION));
I'm attempting to create a gridview that is loaded with images from a specific folder that resides on an SDCard. The path to the folder is known, ("/sdcard/pictures") , but in the examples I've seen online I am unsure how or where to specify the path to the pictures folder I want to load images from. I have read through dozens of tutorials, even the HelloGridView tutorial at developer.android.com but those tutorials do not teach me what i am seeking.
Every tutorial I have read so far has either:
A) called the images as a Drawable from the /res folder and put them into an array to be loaded, not using the SDCard at all.
B) Accessed all pictures on the SDCard using the MediaStore but not specifying how to set the path to the folder I want to display images form
or
C) Suggested using BitmapFactory, which I haven't the slightest clue how to use.
If I'm going about this in the wrong way, please let me know and direct me toward the proper method to do what I'm trying to do.
OK, after many iterations of trying, I finally have an example that works and I thought I'd share it. My example queries the images MediaStore, then obtains the thumbnail for each image to display in a view. I am loading my images into a Gallery object, but that is not a requirement for this code to work:
Make sure you have a Cursor and int for the column index defined at the class level so that the Gallery's ImageAdapter has access to them:
private Cursor cursor;
private int columnIndex;
First, obtain a cursor of image IDs located in the folder:
Gallery g = (Gallery) findViewById(R.id.gallery);
// request only the image ID to be returned
String[] projection = {MediaStore.Images.Media._ID};
// Create the cursor pointing to the SDCard
cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
MediaStore.Images.Media.DATA + " like ? ",
new String[] {"%myimagesfolder%"},
null);
// Get the column index of the image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
g.setAdapter(new ImageAdapter(this));
Then, in the ImageAdapter for the Gallery, obtain the thumbnail to display:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(context);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// obtain the image URI
Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID) );
String url = uri.toString();
// Set the content of the image based on the image URI
int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));
Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(),
originalImageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
i.setImageBitmap(b);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
I guess the most important section of this code is the managedQuery that demonstrates how to use MediaStore queries to filter a list of image files in a specific folder.
You need to do a few more steps than the GridView tutorial on developer.android.com. Using the following tutorial
http://developer.android.com/resources/tutorials/views/hello-gridview.html
You'll want to add a method to create ImageView's of the files from your sd card:
Create/add a Vector to your class variables (to hold a list of ImageViews):
private Vector<ImageView> mySDCardImages;
Initialize the vector:
mySDCardImages = new Vector<ImageView>();
Create a method to load images:
List<Integer> drawablesId = new ArrayList<Integer>();
int picIndex=12345;
File sdDir = new File("/sdcard/pictures");
File[] sdDirFiles = sdDir.listFiles();
for(File singleFile : sdDirFiles)
{
ImageView myImageView = new ImageView(context);
myImageView.setImageDrawable(Drawable.createFromPath(singleFile.getAbsolutePath());
myImageView.setId(picIndex);
picIndex++;
drawablesId.add(myImageView.getId());
mySDCardImages.add(myImageView);
}
mThumbIds = (Integer[])drawablesId.toArray(new Integer[0]);
Then down in your ImageAdapter method, change
imageView.setImageResource(mThumbIds[position]);
to
imageView.setImageDrawable(mySDCardImages.get(position).getDrawable());
Remove from the ImageAdapter the initialization of mThumbIds. (it should be up with the definition of mySDCardImages. Accessible to both class methods.)
(Quick and dirty version) Make sure to test your path, etc and catch any Exceptions.
In your case BitmaFactory might be a good way to go. Example:
File dir = new File( "/sdcard/pictures" );
String[] fileNames = dir.list(new FilenameFilter() {
boolean accept (File dir, String name) {
if (new File(dir,name).isDirectory())
return false;
return name.toLowerCase().endsWith(".png");
}
});
for(string bitmapFileName : fileNames) {
Bitmap bmp = BitmapFactory.decodeFile(dir.getPath() + "/" + bitmapFileName);
// do something with bitmap
}
Not time to test this but should work ;-)
read this link: http://androidsamples.blogspot.com/2009/06/how-to-display-thumbnails-of-images.html
it shows how to use both mediastore and bitmapfactory.
the way you should chose depends on what exactly you need. if you have a static set of images, it's much better idea to put them to drawables, i think, cause this way it's faster and you don't rely on sd card, which can be removed, corrupt or files could be renamed/deleted
if images are dynamic, then use mediastore or bitmap factory. but keep in mind that putting images into array or something it's quite memory consuming, so you can end up having outofmemory exception
Looks like you want custom gallerry, it will take much time for you,
I suggest you get Custom Camera Gallery for your working.
You will get Photos/Videos in Grid View as you want.
for Kotlin code see the answer of this question
the idea is alslo applicable for java (but you need to modify the code)
I am currently making an app which works with images. I need to implement functionality where the user picks a file stored on the SD card. Once they pick the picture (using the Android gallery), the the file-location of the image will be sent to another Activity, where other work will be done upon it.
I have seen similar posts here on SO, but none to answer my question specifically. Basically this is the code I am doing when the user clicks the "Load a Picture" button:
// Create a new Intent to open the picture selector:
Intent loadPicture = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// To start it, run the startActivityForResult() method:
startActivityForResult(loadPicture, SELECT_IMAGE);
From that code, I then have a onActivityResult() method to listen to the call-back:
// If the user tried to select an image:
if(requestCode == SELECT_IMAGE)
{
// Check if the user actually selected an image:
if(resultCode == Activity.RESULT_OK)
{
// This gets the URI of the image the user selected:
Uri selectedImage = data.getData();
// Create a new Intent to send to the next Activity:
Intent i = new Intent(currentActivty.this, nextActivity.class);
// ----------------- Problem Area -----------------
// I would like to send the filename to the Intent object, and send it over.
// However, the selectedImage.toString() method will return a
// "content://" string instead of a file location. How do I get a file
// location from that URI object?
i.putExtra("PICTURE_LOCATION", selectedImage.toString());
// Start the activity outlined with the Intent above:
startActivity(i);
As the code above states, the uri.toString() will return a content:// string instead of the file location of the selected picture. How do I obtain the file location?
Note: Another possible solution is to send over the content:// string and convert that into a Bitmap (which is what happens in the next Activity). However, I don't know how to do that.
I have found the answer to my own question. After doing some more searching, I finally stumbled upon a post here on SO which asks the same question here: android get real path by Uri.getPath().
Unfortunately, the answer has a broken link. After some Google searching, I found the correct link to the site here: http://www.androidsnippets.org/snippets/130/ (I have verified that this code does indeed work.)
However, I decided to take a different route. Since my next Activity is using an ImageView to display the picture, I am instead going to use the Uri content string for all methods that link to the next Activity.
In the next Activity, I am using the ImageView.setImageUri() method.
Here is the code I am doing in the next Activity to display the picture from the content:// string:
// Get the content string from the previous Activity:
picLocation = getIntent().getStringExtra("PICTURE_LOCATION");
// Instantiate the ImageView object:
ImageView imageViewer = (ImageView)findViewById(R.id.ImageViewer);
// Convert the Uri string into a usable Uri:
Uri temp = Uri.parse(picLocation);
imageViewer.setImageURI(temp);
I hope that this question and answer will be helpful to future Android developers.
Here's another answer that I hope someone finds useful:
You can do this for any content in the MediaStore. In my app, I have to get the path from URIs and get the URI from paths. The former:
/**
* Gets the corresponding path to a file from the given content:// URI
* #param selectedVideoUri The content:// URI to find the file path from
* #param contentResolver The content resolver to use to perform the query.
* #return the file path as a string
*/
private String getFilePathFromContentUri(Uri selectedVideoUri,
ContentResolver contentResolver) {
String filePath;
String[] filePathColumn = {MediaColumns.DATA};
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
The latter (which I do for videos, but can also be used for Audio or Files or other types of stored content by substituting MediaStore.Audio (etc) for MediaStore.Video:
/**
* Gets the MediaStore video ID of a given file on external storage
* #param filePath The path (on external storage) of the file to resolve the ID of
* #param contentResolver The content resolver to use to perform the query.
* #return the video ID as a long
*/
private long getVideoIdFromFilePath(String filePath,
ContentResolver contentResolver) {
long videoId;
Log.d(TAG,"Loading file " + filePath);
// This returns us content://media/external/videos/media (or something like that)
// I pass in "external" because that's the MediaStore's name for the external
// storage on my device (the other possibility is "internal")
Uri videosUri = MediaStore.Video.Media.getContentUri("external");
Log.d(TAG,"videosUri = " + videosUri.toString());
String[] projection = {MediaStore.Video.VideoColumns._ID};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
Log.d(TAG,"Video ID is " + videoId);
cursor.close();
return videoId;
}
Basically, the DATA column of MediaStore (or whichever sub-section of it you're querying) stores the file path, so you use what you know to look up the DATA, or you query on the DATA field to select the content you care about.