Thursday, January 7, 2010

How to display a JPG in sdcard on ImageView

To display a JPG on ImageView, BitmapFactory.decodeFile() can be used.

display JPG on ImageView

But, in my experience, if I try to display a original photo in 10.0 million pixels by Nikon D80, the application will be stopped unexpectedly. So I have to use options.inSampleSize to reduce sample size.



In this exercise, the source (myJpgPath) of the JPG file is fixed, "/sdcard/DSC_3509.JPG". You have to modify to suit your own case.

Modify main.xml to have a TextView and ImageView to display files name and the photo.
<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/jpgname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:id="@+id/jpgview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>


Modify the java file
package com.exercise.AndroidJpgView;

import java.io.File;

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

public class AndroidJpgView extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView jpgName = (TextView)findViewById(R.id.jpgname);
ImageView jpgView = (ImageView)findViewById(R.id.jpgview);

String myJpgPath = "/sdcard/DSC_3509.JPG"; //UPDATE WITH YOUR OWN JPG FILE

jpgName.setText(myJpgPath);

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bm = BitmapFactory.decodeFile(myJpgPath, options);
jpgView.setImageBitmap(bm);
}
}


Download the files.



10 comments:

Nikola Vasilev said...

Thanks a lot!!!

GeyikCenter said...

Very nice, Soo Thanks

Tecnolaser, C.A. said...

I was looking for a solution like this, perfect!!! Thnks So Much!!

It is My Day said...

Good Work!

Unknown said...

can a file on sdcard be saved with a image in it and retrived back

Erik said...

hello Ramya A,

Please read Save file to SD Card.

Unknown said...

Awesome =)
This options has saved my life:
options.inSampleSize = 2;
I was using = 32 without success.

Congratulations for the blog.

Anonymous said...

wow! thank you very much! Just had this problem! great!

Anonymous said...

thanks a lot....

rja said...

Supeerb you solve my problem