How to download a image from URL in App

后端 未结 5 512
长情又很酷
长情又很酷 2021-01-03 14:40

I\'d like to know how I can download an Image from a given URL and display it inside an ImageView. And is there any permissions required to men

5条回答
  •  执念已碎
    2021-01-03 15:18

    look this:

    Option A:

    public static Bitmap getBitmap(String url) {
        Bitmap bm = null;
        try {
            URL aURL = new URL(url);
            URLConnection conn = aURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
            bis.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return bm;
    }
    

    Option B:

    public Bitmap getBitmapFromURL(String src) {
        try {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            input.close();
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    

    Jus run the method in a background thread.

提交回复
热议问题