无法在imageview中显示图像

时间:2014-03-08 03:26:00

标签: java android 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();
    }
}

我可以看到错误消息“myBitmap is NULL”。 有什么我需要做的,以确保路径被识别。

谢谢!

2 个答案:

答案 0 :(得分:1)

路径"C:\\photos\\a.jpg"是指Windows系统中的路径,这是无效的。 Android对Windows一无所知。

您需要将文件放在资源目录或资产目录中,并相应地提供路径。

答案 1 :(得分:1)

试试这个: 将图像放在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;
}

然后将imageView中的图像位图设置为:

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

或者如果图像文件在SD card上,请尝试:

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

希望这会对你有所帮助。

相关问题