Monday, November 21, 2011

Loading image from sdcard

In this tutorial I show how to load an image from sdcard to ImageView in android.
main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

LoadImageFromSDCardActivity.java

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

public class LoadImageFromSDCardActivity extends Activity {
    /** Called when the activity is first created. */
   
    private Bitmap bitmap;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
// BitmapFactory creates a bitmap from various sources, including files, streams and byte arrays.
//decodeFile() methods decodes a file path into a bitmap.
        bitmap=BitmapFactory.decodeFile("/sdcard/IMG_1993.jpg");
        ImageView imageView=(ImageView)findViewById(R.id.imageView1);

 //to set the bitmap as the content of ImageView
        imageView.setImageBitmap(bitmap);
    }
}

In the above java file "IMG_1993.JPG"  is a name of the image which we are loading from sdcard to Imageview. To load this image first we have to put this image into sdcard. To put this image into sdcard follow the steps below.
Start the emulator first, then open DDMS perspective, open FileExplorer in DDMS perspective click on "mnt" folder, then click on sdcard. Click on the "Push a file on to the device" button on the top of the FileExplorer, it opens Put file on Device window  select an image to push and click Open. Then  the image is pushed into sdcard..
 
Now run the program and you will see the out put on your emulator.


1 comment: