How to load image from sdcard in android

Here I have added coding for load image from sd card and set it to the Imageview in android.

Sometimes you need to load the images from the sdcard or from some other location. Here is the example for load an image from sdcard in android.

Steps to load image from sdcard in android

  • Get the exact image path in sdcard.
  • Create Bitmap from the image path.
  • Set the bitmap into imageview.

Step 1 – Get the exact image path in sdcard

By using system intent, browse the android file system and get the exact path of the image. That you want to set in the imageview. In my case, /mnt/sdcard/DCIM/100ANDRO/DSC_0002.jpg is the path of the image in the sdcard.

Step 2 – Create Bitmap from the image path

BitmapFactory

android.graphics.BitmapFactory class provides a method decodeFile(String pathName) to decode a file path into a bitmap. decodeFile() method return the Bitmap as the response.

The decoded bitmap can be loaded to ImageView using setImageBitmap() method of the ImageView.

For that, you have to do some simple step to load the image from sdcard.

First, create Imageview to set image.

And create an object for  BitmapFactory.Options for the bitmap image. If you like to resize the image, you can set the size for the image.

options.inSampleSize = 8;

Then, Decode the image file from the particular directory and set it to the Bitmap Image.

final Bitmap b = BitmapFactory.decodeFile("/mnt/sdcard/DCIM/100ANDRO/DSC_0002.jpg",options)

Step 3 – Set the bitmap into imageview

Finally, set the bitmap image to the Imageview.

iv.setImageBitmap(b);

load image from sdcard example

MainActivity.Java

public class MainActivity extends Activity {
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 final ImageView iv = (ImageView)findViewById(R.id.imageView1);
 BitmapFactory.Options options = new BitmapFactory.Options();
 // will results in a much smaller image than the original
 options.inSampleSize = 8;
 final Bitmap b = BitmapFactory.decodeFile("/mnt/sdcard/DCIM/100ANDRO/DSC_0002.jpg", options);
 iv.setImageBitmap(b);
 }
}

Related Post

Custom dialog in android example

Custom font in android example

Splash screen in android


2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top