Monday, January 30, 2012

Loading a image from sdcard in different ways?



Android - Load a image in a file (not drawable) as image in the layout

Sometimes, it is easier load a image from other directory (sdcard, for example) 
than load a image from drawable because for this last case, the image should be
 stored in the directory res/drawable first and packaged along with the apk files.

To load a image from a directory, it should be converted to the drawable first. 
Here comes a piece of code which can help:

File file = new File ("/sdcard/1.jpg");
ImageView imageView = (ImageView) findViewById(R.id.icon);
imageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));

Be warning that there is another method for ImageView called setImageURI(URI uri).
 This method is used to load external files, it doesn't work with the type file.
 For example, this code won't work:


File file = new File ("/sdcard/1.jpg");
ImageView imageView = (ImageView) findViewById(R.id.icon);
imageView.setImageURI(Uri.fromFile(file));
--------------------------------------------------------------------------------------------------------------------------------
The another way to use image from sdcard you can write the following code...........


imagePath="/sdcard"+"/"+filename;
try {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageview.setImageBitmap(bitmap);

} catch (Exception e) {
e.printStackTrace();
File photos= new File("/sdcard/", "/Wockhardt/"+selectedFolderName+"/"+filename);
Bitmap b = decodeFile(photos);
imageview.setImageBitmap(b);



private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);


            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale++;
            }


            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }

1 comment:

  1. no this is not helpfull plese update your webside and link

    ReplyDelete