How to get Bitmap from an Uri?

前端 未结 16 1370
时光说笑
时光说笑 2020-11-22 10:41

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 u

16条回答
  •  鱼传尺愫
    2020-11-22 11:04

    . . IMPORTANT: See answer from @Mark Ingram below and @pjv for at better solution. . .

    You could try this:

    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;
    }
    

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

提交回复
热议问题