简体   繁体   中英

Android load image from URL into Bitmap object

I'm trying to load an image from URL into Bitmap object, but I always end up with NetworkInUIThread kind of exception. Can anyone provide me a library for this?

Note, that I'm not trying to put the image into ImageView, I want to put it into Bitmap object first, as it will be used more times later in my app.

I found this code in some other StackOverflow thread, but it doesn't work.

public static 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);
        return myBitmap;
    }catch(IOException e){
        return null;
    }
}

Put this code inside the doInBackground method of an AsyncTask

eg

private class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
    protected Bitmap doInBackground(String... params) {
        try {
            URL url = new URL(params[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch(IOException e) {
            return null;
        }
    }

    protected void onPostExecute(Bitmap result) {
         //do what you want with your bitmap result on the UI thread
    }

}

and call it in your activity by:

new MyAsyncTask().execute(src);
    try {
        URL url = new URL("http://....");
        Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    } catch(IOException e) {
        System.out.println(e);
    }

try

        Bitmap bitmap = null;
        InputStream iStream = null;
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(5000 /* milliseconds */);
        conn.setConnectTimeout(7000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        iStream = conn.getInputStream();
        bitmap = BitmapFactory.decodeStream(iStream);

You can use Glide To download image from server and store it in Bitmap Object.

Bitmap theBitmap = Glide.
    with(this).
    load("http://....").
    asBitmap().
    into(100, 100). // Width and height
    get();

Please Refer this to add glide dependency in your app -> https://github.com/bumptech/glide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM