安卓将图像从URL加载到位图对象中



我正在尝试将图像从URL加载到位图对象中,但我总是以NetworkInUIThread类型的异常结束。任何人都可以为此提供图书馆吗?

请注意,我不是要尝试将图像放入 ImageView 中,而是想先将其放入 Bitmap 对象中,因为它稍后将在我的应用程序中使用更多次。

我在其他一些 StackOverflow 线程中找到了这段代码,但它不起作用。

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

将此代码放在AsyncTaskdoInBackground 方法中

例如

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

并通过以下方式在您的活动中调用它:

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

试试

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

您可以使用 Glide 从服务器下载图像并将其存储在位图对象中。

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

请参考此内容以在您的应用程序中添加滑动依赖项 -> https://github.com/bumptech/glide

最新更新