Android: Display Image from SD CARD

后端 未结 4 1774
栀梦
栀梦 2020-11-27 06:53

This is driving me insane! Here\'s my code (I know this file exists):

File imageFile = new File(\"/sdcard/gallery_photo_4.jpg\");
ImageView jpgView = (Image         


        
相关标签:
4条回答
  • 2020-11-27 07:03

    This code worked for me finally:

        setContentView(R.layout.main);
        ImageView jpgView = (ImageView)findViewById(R.id.imageView);
        Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/sample-1.jpg");
        jpgView.setImageBitmap(bitmap);
    

    Crash was happening because setContentView() was not performed before attaching the jpgview:

    code that was crashing:

        ImageView jpgView = (ImageView)findViewById(R.id.imageView);
        Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/sample-1.jpg");
        jpgView.setImageBitmap(bitmap);
        setContentView(R.layout.main);
    
    0 讨论(0)
  • 2020-11-27 07:06

    I would rather use a BitmapFactory to decode the Image from the file-path:

    Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
    jpgView.setImageBitmap(bitmap);
    

    The Docs say:

    If the specified file name is null, or cannot be decoded into a bitmap, the function returns null.

    Can you check if the code works with another image and if you can open your image on your PC thought. Maybe the file is corrupt.

    0 讨论(0)
  • 2020-11-27 07:08
    String imagePath = Environment.getExternalStorageDirectory().toString() + PATH_TO_IMAGE;
    return Drawable.createFromPath(imagePath)
    
    0 讨论(0)
  • 2020-11-27 07:14

    USE THIS LINE OF CODE FOR GETTING IMAGE FROM SDCARD. AND THEN DISPLAY IT IN YOUR IMAGEVIEW

    where "FileInputOutput" is a folder in your sdcard

        String path = Environment.getExternalStorageDirectory()+ "/FileInputOutput/img1.jpg"; 
                File imgFile = new File(path);
                if(imgFile.exists())
            {
                    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());                  
                    ImageView myImage = (ImageView) findViewById(R.id.imageView1);
                    myImage.setImageBitmap(myBitmap);
            }
                else                    
                    Toast.makeText(v.getContext(),"no IMAGE IS PRESENT'",Toast.LENGTH_SHORT).show();
            }
    
    0 讨论(0)
提交回复
热议问题