2015年7月21日 星期二

Read an image file into bitmap and set it to the imageview

AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

如果沒有加 Permission,image file會無法被讀取,導致 ImageView無法正常顯示

Java
private static final String INTERNAL_STORAGE_PATH = "/storage/sdcard0";
private static final String FILE_NAME = "image.jpg";
private ImageView mImageView;
protected void onCreate(Bundle savedInstanceState) {
......
        mImageView = (ImageView)findViewById(R.id.origin_view);

        // From internal storage
        File imageFile = new File(INTERNAL_STORAGE_PATH + "/" + FILE_NAME);       
        Bitmap imageBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());

        // From external storage (SD card)
        File imageFile = new File(Environment.getExternalStorageDirectory() + "/" + FILE_NAME);
        Bitmap imageBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());

        // From app resource
        Bitmap imageBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);

        mImageView.setImageBitmap(imageBitmap);      
}
 

沒有留言: