Friday, 10 May 2013

how to load image from sdcard in android

how to load an image from sd card in android studio

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 sd card or from some other location.Here is the example for load an image from sd card in android.

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.

ForThat you have to do some simple step to load the image from sd card.
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",

finally,set the bitmap image to the Imageview.

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

Please provide your feedback.

No comments: