2 hcg 21 hcg_21 于 2012.10.10 14:16 提问

加载远程图像到ImageView,但没有加载上

我使用以下函数加载一个远程图像到ImageView。图像存在于URL,我想从URL中加载图像,但当我调用函数想显示图像时, ImageView仍是空白。为什么会出现这种情况啊?

public static void setImage(ImageView view, String url) throws IOException { 

        final URLConnection conn = new URL(url).openConnection(); 
        conn.connect(); 
        final InputStream is = conn.getInputStream(); 

        final BufferedInputStream bis = new BufferedInputStream(is, 100000); 

        final Bitmap bm = BitmapFactory.decodeStream(bis); 
        bis.close(); 
        is.close(); 

        view.setImageBitmap(bm); 
    } 

2个回答

myc_100
myc_100   2012.10.10 14:59
已采纳

通过下面的代码能够加载远程图像到ImageView:

 Bitmap bitmap = null;

    HttpGet httpRequest = null;


    try {
            URL url = new URL(your_url);
            httpRequest = new HttpGet(url.toURI());

            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); 
            InputStream instream = bufHttpEntity.getContent();
            bitmap = BitmapFactory.decodeStream(instream);
    } catch (URISyntaxException e) {
            e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
    }
csh_34
csh_34   2012.10.10 16:22
private void setImage(String urlStr, ImageView iv) throws ClientProtocolException, IOException { 
    DefaultHttpClient httpClient = new DefaultHttpClient(); 
    HttpGet request = new HttpGet(urlStr); 
    HttpResponse response = httpClient.execute(request); 
    InputStream is = response.getEntity().getContent(); 
    TypedValue typedValue = new TypedValue(); 
    typedValue.density = TypedValue.DENSITY_NONE; 
    Drawable drawable = Drawable.createFromResourceStream(null, typedValue, is, "src"); 
    iv.setImageDrawable(drawable); 
} 

注意:它是同步加载的。如果它执行到下一步,应该加载到另一个线程,而不会限制主线程。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!