How to display a JPG in sdcard on ImageView


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.


android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
android:id="@+id/jpgname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
android:id="@+id/jpgview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>



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

留言

此網誌的熱門文章

【教學】減少手動設定:讓 iPad 自動連接 iPhone 熱點