从Web上提取图像

时间:2010-09-22 22:49:07

标签: android bitmap gallery

我正在使用以下代码从网上抓取图片。它使用Gridview并根据位置从数组中选择一个URL。它工作但图像的加载经常被击中或错过。几乎每次我启动应用程序时,都会加载不同数量的图像。

从纵向视图更改为横向视图时也会出现问题,可能会显示10个图像中的5个然后我将转动设备并且通常会丢失所有图像。有时会有一些人出现。

有关使其更加强大的任何想法吗?

try {
                    URLConnection conn = aURL.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    Bitmap bm = BitmapFactory.decodeStream(bis);
                    bis.close();
                    return bm;
            } catch (IOException e) {
                    Log.d("DEBUGTAG", "error...");
            }
            return null;

1 个答案:

答案 0 :(得分:1)

我读到的一件事是,从InputStream解码位图有一个已知的错误,Google建议的修复是使用FlushedInputStream(以下URL中的示例):

http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html

另外,我将下载代码放入AsyncTask中。以下是我目前使用的内容:

public static Bitmap loadImageFromUri(URI uri)
    {   
        URL url;
        try {
            url = uri.toURL(); 
        } catch (MalformedURLException e) {
            Log.v("URL Exception", "MalformedURLException");
            return null;
        }

        try
        {           
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            return BitmapFactory.decodeStream(new FlushedInputStream(input));
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
    }

由于我已经设置了其余代码的方式,我只传入了一个URI,您可以传入一个URL而跳过第一部分。这将使下载不会占用您的UI线程。

相关问题