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

有谁知道如何实现这一目标?

最佳答案



重要提示:有关更好的解决方案,请参见下面@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。

10-08 07:50