Wednesday, June 10, 2009

How to Display Thumbnails of Images Stored in the SD Card



Using the following example we can display the thumbnails of images stored in the sd card. Here im displaying the thumbnails in the Grid view.
You should to add the folowing permission in the manifest xml file.
< uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
Sd card should be available with the emulator or real device.

ImageThumbnailsActivity is the main Activity.

AndroidManifest.xml
--------------------
<?xml version="1.0" encoding="utf-8"?>
< manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="image.Thumbnails" android:versionCode="1" android:versionName="1.0.0">
      < uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
      < application android:icon="@drawable/icon" android:label="@string/app_name">
            < activity android:name=".ImageThumbnailsActivity"
                  android:label="@string/app_name">
                  < intent-filter>
                        < action android:name="android.intent.action.MAIN" />
                        < category android:name="android.intent.category.LAUNCHER"/>
                  </intent-filter>
            </activity>
            < activity android:name=".ViewImage">
                  < intent-filter>
                        < action android:name="android.intent.action.VIEW" />
                        < category android:name="android.intent.category.DEFAULT" />
                  </intent-filter>
            </activity>
      </application>
</manifest>

package image.Thumbnails;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

public class ImageThumbnailsActivity extends Activity {
      /** Called when the activity is first created. */
      private Cursor imagecursor, actualimagecursor;
      private int image_column_index, actual_image_column_index;
      GridView imagegrid;
      private int count;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            init_phone_image_grid();
      }
      private void init_phone_image_grid() {
            String[] img = { MediaStore.Images.Thumbnails._ID };
            imagecursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, img, null,
null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
            image_column_index = imagecursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
            count = imagecursor.getCount();
            imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
            imagegrid.setAdapter(new ImageAdapter(getApplicationContext()));
            imagegrid.setOnItemClickListener(new OnItemClickListener() {
                  public void onItemClick(AdapterView parent, View v,
int position, long id) {
                        System.gc();
                        String[] proj = { MediaStore.Images.Media.DATA };
                        actualimagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
null, null, null);
                        actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        actualimagecursor.moveToPosition(position);
                        String i = actualimagecursor.getString(actual_image_column_index);
                        System.gc();
                        Intent intent = new Intent(getApplicationContext(), ViewImage.class);
                        intent.putExtra("filename", i);
                        startActivity(intent);
                  }
            });
      }


      public class ImageAdapter extends BaseAdapter {
            private             Context mContext;
            public ImageAdapter(Context c) {
                  mContext = c;
            }
            public int getCount() {
                  return count;
            }
            public Object getItem(int position) {
                  return position;
            }
            public long getItemId(int position) {
                  return position;
            }
            public View getView(int position,View convertView,ViewGroup parent) {
                  System.gc();
                  ImageView i = new ImageView(mContext.getApplicationContext());
                  if (convertView == null) {
                        imagecursor.moveToPosition(position);
                        int id = imagecursor.getInt(image_column_index);
                        i.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
+ id));
                        i.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        i.setLayoutParams(new GridView.LayoutParams(92, 92));
                  }
                  else {
                        i = (ImageView) convertView;
                  }
                  return i;
            }
      }
}

// By selecting the thumbnails user can view the actual image.
package image.Thumbnails;

import android.os.Bundle;
import android.widget.ImageView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ViewImage extends Activity {
      private String filename;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            System.gc();
            Intent i = getIntent();
            Bundle extras = i.getExtras();
            BitmapFactory.Options bfo = new BitmapFactory.Options();
            bfo.inSampleSize = 2;
            filename = extras.getString("filename");
            ImageView iv = new ImageView(getApplicationContext());
            Bitmap bm = BitmapFactory.decodeFile(filename, bfo);
            iv.setImageBitmap(bm);
            setContentView(iv);
      }
}



//main.xml

< ?xml version="1.0" encoding="utf-8"?>
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
< GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/PhoneImageGrid" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:numColumns="auto_fit"
android:verticalSpacing="10dp" android:horizontalSpacing="10dp"
android:columnWidth="90dp" android:stretchMode="columnWidth"
android:gravity="center" />
< /LinearLayout>

68 comments:

  1. I've completed very similar code but am struggling with getting thumbnails in my emulator SD card. I have added folders just as they appear on my phone's SD card but when I get a count on the number of thumbnails there are based on the thumbnail external content URI, the count is always zero. Can you help me understand what I'm missing here???

    ReplyDelete
  2. hi,
    I didnt create any folders in my SD card. But later i found two folders named as albumthumbs and dcim after copying some image files to SD card. Do you have the same? Can you Check it?
    Thanks.

    ReplyDelete
  3. not as fluently as in default app Gallery....
    could you find which part slows this activity down?
    Thx!

    ReplyDelete
  4. the bug in this application is that *.JPG images will not be shown while *.jpg are present.

    ReplyDelete
  5. actually that wasnt the problem ...

    the problem is ..if you add images and dont open the gallery before using this app..
    opening the gallery makes thumbnails ... after which the images show up in the app in the right place

    ReplyDelete
  6. when i run this application images are reapeated afeter some images so any soultion ofr that issue?

    ReplyDelete
  7. Jaimin, i have the same problem.
    Beside the scroll function works very slow.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Hi Ramesh,

    There is nothing getting displayed on the Emulator.I followed the same stuff.My sd card has got .jpeg files.Count value is always zero.Could you tell me where I am going wrong

    ReplyDelete
  10. Ramesh - go to menu, dev tools, and media scanner. seems to be a bug in the emulator. Then go back and you should she the images.

    ReplyDelete
  11. Hi,
    I don't understand why this is too complicated just to display a full image from a list.
    I'm coming from web applications dev and I'm new on android developpement but I found that too heavy to develop basic action like displaying a big image from a small one.
    Is android really matters ?

    ReplyDelete
  12. Thanks for the post! I was able to run this app. How do I get pictures from a specific folder? Do I need to change the query?

    ReplyDelete
  13. thanks man!!! for the fabulous code. it helps me a lot

    ReplyDelete
  14. Why do not you use this class : http://developer.android.com/reference/android/provider/MediaStore.Images.Thumbnails.html

    and I think there is also this problem : "the problem is ..if you add images and dont open the gallery before using this app..". The thumbnail are only created by the gallery...

    ReplyDelete
  15. how did you store your images in the sdcard?

    ReplyDelete
  16. Hello, nice tutorial but on my Nexus (2.2) I always get the following error:

    W/ImageView( 4232): Unable to open content: content://media/external/images/thumbnails/1
    I/System.out( 4232): resolveUri failed on bad bitmap uri: content://media/external/images/thumbnails/1

    Do you have an idea what I should change?

    ReplyDelete
  17. On Windows, run DDMS perspective and you can access the simulated file system ......

    ReplyDelete
  18. hi
    but this code is not working for OS version 1.5 and 1.6 . do you have any other solution which is commen for both 1.5 and 2.0

    ReplyDelete
  19. Hi Dear,
    I used your code but did not display any image in device what can i do,please give any solution for display image in device

    ReplyDelete
  20. Thank you very much, I looked over the web for such example, work great on my Nexus one.

    ReplyDelete
  21. i cant even begin to tell you how awesome you are...

    ReplyDelete
  22. Man I am realy very thank ful..
    I just copied the code and every thing worked fine.

    Gr8 work man ..
    Thanks once again

    ReplyDelete
  23. Hello 2All,

    I am new in Android.
    First of all thanks for this tutorial.
    But I have one doubt:
    "Can anyone suggest me that what is the location of all that pictures.
    I mean to say that from where all the pictures are seen in the Greed View?"

    ReplyDelete
  24. Latest reviews and news about android phones, free droid app and android mobile


    free android app

    ReplyDelete
  25. Sometimes I receive the wrong image with this code, is there any fix to this?

    ReplyDelete
  26. ImageAdapter getView is completely wrong. You should update image uri every time, not just in cases where convertView is null - this will fix wrong and repeated images problem. Also these gc scares me much.

    ReplyDelete
  27. hi,

    when i click the thumbnail image it does not view the next class can anybody help me i's very urgent pls

    ReplyDelete
  28. Sorry guys,

    It will work if any idea for zooming is images.pls reply for me.

    thanks.

    ReplyDelete
  29. Sorry guys,

    It will work if any idea for zooming this image.pls reply for me

    thanks.

    ReplyDelete
  30. Any one please tell how to Parse image from url in Gridview.I am unable to find any example

    ReplyDelete
  31. Thanks man for great code.
    But can any buddy tell me how to increase there performance during scroll. Because it is not as fluent as default apps.

    ReplyDelete
  32. how can i change the size of the displayed image.

    ReplyDelete
  33. I keep running into OutOfMemoryException on my ADP2 phone, each time I scroll down the GridView.

    Has anyone run into the same problem?

    ReplyDelete
  34. This comment has been removed by the author.

    ReplyDelete
  35. What if you just wanted to display the pics that are in your camera folder


    /sdcard/DMIC/Camera

    ReplyDelete
  36. This works fine for me to retrieve images from sd card. But im trying to display the clicked image in another Activity where i have an ImageView and some buttons in that layout. Please help me.

    ReplyDelete
  37. How to display images from a folder dynamically, like pictures stored in application data directory "/data/data/com.packagename/images/".

    ReplyDelete
  38. *** Get Your FREE FACEBOOK T-Shirt, Register Now http://goo.gl/MwZGv ***

    ReplyDelete
  39. Hi Dave, I just copy pasted the code .But nothing is showing?why its so?

    ReplyDelete
  40. How do you access photos in the Pictures folder on the device? How should the URI look? Like the photos taken with the device?

    ReplyDelete
  41. hi i have also same problem

    ReplyDelete
  42. Thanks for the article. the code worked for me.

    ReplyDelete
  43. hey how can i show image's name also.

    ReplyDelete
  44. I posted some code updates in the following blog entry:
    http://www.selikoff.net/2011/07/12/improving-the-custom-android-gallery/

    ReplyDelete
  45. The implementation I'm attempting allows a user to take a photo of a person or place. That photo is saved on the SD card and the image URI is stored in SQLite. Then I want them to be able to view the images later. If they open details for a specific person my app will query the database for all image URI's associated with that person and show a gallery of clickable thumbnails. I've gotten to the point of taking the pictures, but I cannot redisplay them in the gallery. Is this possible? A gallery of thumbnails from stored URIs?

    ReplyDelete
  46. Hey this code worked for me... thanks for that but i wanna know how to show the photos from camera i.e. DCIM folder. means everytime we take new photos it should be visible in grid view also... plz help me for this... i will be thankfull...

    ReplyDelete
  47. Thanks! it help me. I have a question: if my internet connection is too slow, how show a ProccessDialog to show a waiting message?

    Thanks again!!
    http:\\www.tutorialandroid.com

    ReplyDelete
  48. sorry, i just read your blog. it is really useful. But, i don't know how to give a specific folder path. Can you show me?

    ReplyDelete
  49. This comment has been removed by the author.

    ReplyDelete
  50. This code doesnt work on honeycomb... The method is deprecated... Kindly post a relevant tutorial for Honeycomb Thanks....

    ReplyDelete
  51. Hey dude..!
    It's Really working fine.. thanks for that..!
    Could you please help me to download images from the URL and store in a temporary folder..?

    ReplyDelete
  52. how to give a specific folder path. Can you show me?

    ReplyDelete
    Replies
    1. You can specify your folder path as 4th parameter as shown below:

      cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
      projection,
      MediaStore.Images.Media.DATA + " like ? ",
      new String[] {"%sdcard/mypics%"},
      null);

      Delete
  53. i do same thing but can`t working this code.i create two folder in side the sdcard as like you do.after copy some images from them but when i fetch the image id the cursor will be null value.how to slove this.plz say me the way it`s urgent.
    Thanks in Advance

    ReplyDelete
    Replies
    1. hai please try this one. after u insert the images in the sdcard then open the emulator gallery and check the images are there.. if it is there once again run the code.. it will work.. i had also the same problem i did the same thing. try this reply what u will get..

      Delete
  54. thank you very much..i was searched this for long time. i saw many blogs but i was not satisfied about their codes. today only i saw your blog it was really superb. thank you once again..... keep posting like this

    ReplyDelete
  55. Here its so many errors !!!

    ReplyDelete
  56. This works great for loading what's in the standards gallery, however if i change the first managedQuery to point to my folder (saved in root of sdcard) then no results are returned.

    I know that the location is correct as if i instead change the second managedQuery to point to my folder then when i click on a thumbnail it loads one of the images from that folder instead, proving it can see it on some level.

    The images in that folder are loaded on externally rather than being taken by the phones camera so don't know if possibly these images are not in a library or have meta info or something perhaps?

    String[] img = { MediaStore.Images.Thumbnails._ID };
    imagecursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, img, MediaStore.Images.Thumbnails.DATA + " like ? ",new String[] {"%sdcard/myfolder%"}, null);
    image_column_index = imagecursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);

    ReplyDelete
  57. Could someone tell me why thumbnail isn't displayed?

    ReplyDelete
  58. and beautify your code?
    easy for others to take a look!

    ReplyDelete
  59. This tutorial is helpful to me but how i can read all types of images from sd ?
    i mean jpg and png etc. and one more thing it is so slow to load images.

    ReplyDelete
  60. Dear i have an issue in my code, i have made a provision for call obstruct any number.assuming that i do obstruct a number and when i occupied with other call then if blocked number call me at that point all calls are close. it would be ideal if you let me know splution when blocked number call me then not distrub my others call.

    Android App Creator // iPhone Application Development // Android App Maker

    ReplyDelete