简体   繁体   English

无法在Imageview中显示图像

[英]Unable to display image in imageview

I'm trying to display a image in the imageview. 我正在尝试在imageview中显示图像。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageView imageView = (ImageView)findViewById(R.id.imageView1);
    try {
        File imgFile = new File("C:\\photos\\a.jpg");
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                    if (myBitmap == null) {
            Log.e("BITMAP", "myBitmap is NULL");
        }
        imageView.setImageBitmap(myBitmap);         
    }catch (Exception e) {
        e.printStackTrace();
    }
}

I can see the error message "myBitmap is NULL". 我可以看到错误消息“ myBitmap为NULL”。 Is there anything i need to do, to ensure the path is recognized. 有什么我需要做的,以确保路径被识别。

Thanks! 谢谢!

The path "C:\\\\photos\\\\a.jpg" refers to a path in your Windows system, and this is invalid. 路径"C:\\\\photos\\\\a.jpg"是指Windows系统中的路径,该路径无效。 Android doesn't know anything about Windows. Android对Windows一无所知。

You need to put the file in your resources directory or your assets directory, and provide the path accordingly. 您需要将文件放在资源目录或资产目录中,并相应地提供路径。

try this : place image in assets folder and then: 试试这个:将图像放在assets文件夹中,然后:

private Bitmap getBitmapFromAsset(String strName)
{
    AssetManager assetManager = getAssets();
    InputStream istr = null;
    try {
        istr = assetManager.open(strName);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    return bitmap;
}

and then set image Bitmap in imageView as: 然后在imageView中将图像位图设置为:

imageView.setImageBitmap(getBitmapFromAsset("fileName")); 

Or if image file is on SD card then try this : 或者,如果图像文件在SD card尝试以下操作:

File f = new File("/mnt/sdcard/photo.jpg");
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
imageView.setImageBitmap(bmp);

hope this will help you. 希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM