如何从Uri获取位图? [英] How to get Bitmap from an Uri?

查看:131
本文介绍了如何从Uri获取位图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Uri获取位图对象(如果我成功将其存储在 /data/data/MYFOLDER/myimage.pngfile///data/data/MYFOLDER/myimage.png)可以在我的应用程序中使用它?

How to get a Bitmap object from an Uri (if I succeed to store it in /data/data/MYFOLDER/myimage.png or file///data/data/MYFOLDER/myimage.png) to use it in my application?

有人对如何做到这一点有想法吗?

Does anyone have an idea on how to accomplish this?

推荐答案

. . 重要提示:有关更好的解决方案,请参见下面@Mark Ingram和@pjv的答案. .

您可以尝试以下方法:

public Bitmap loadBitmap(String url)
{
    Bitmap bm = null;
    InputStream is = null;
    BufferedInputStream bis = null;
    try 
    {
        URLConnection conn = new URL(url).openConnection();
        conn.connect();
        is = conn.getInputStream();
        bis = new BufferedInputStream(is, 8192);
        bm = BitmapFactory.decodeStream(bis);
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
    finally {
        if (bis != null) 
        {
            try 
            {
                bis.close();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
        if (is != null) 
        {
            try 
            {
                is.close();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
    }
    return bm;
}

但是请记住,仅应在线程(而不是GUI -thread)内调用此方法.我是AsyncTask.

But remember, this method should only be called from within a thread (not GUI -thread). I a AsyncTask.

这篇关于如何从Uri获取位图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆