0

我需要从 http 加载图像,我正在使用以下代码:

                        Bitmap bitmap;                        
                        InputStream is = null;
                        try {
                            is = (InputStream) new URL("www.TESTWEBSITE.com/TEST.JPG").getContent();
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }



                        bitmap = BitmapFactory.decodeStream(is);

但位图仍然是空的..有什么帮助吗?

4

1 回答 1

1

更新:这是执行您想要的完整快照:

        Bitmap bitmap = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("www.TESTWEBSITE.com/TEST.JPG");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream is = urlConnection.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

请确保在 UI 线程之外运行它,例如在其他人评论的 AsyncTask 中。您可以出于实验目的在主线程中尝试它,但要为 ANR 做好准备。

于 2013-10-28T19:51:10.343 回答