如何使用Picasso或Universal Android Loader检索位图?

时间:2014-05-04 22:27:57

标签: android bitmap universal-image-loader picasso

这是我的执行代码:

  public Bitmap downloadBitmap(String url) {
    Bitmap bitmap = null;

    // initilize the default HTTP client object
    final DefaultHttpClient client = new DefaultHttpClient();

    //forming a HttpGet request 
    final HttpGet getRequest = new HttpGet(url);
    try {

        HttpResponse response = client.execute(getRequest);
        //check 200 OK for success
        final int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            Log.w("ImageDownloader", "Error " + statusCode + 
                    " while retrieving bitmap from " + url);
            return null;

        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                // getting contents from the stream 
                inputStream = entity.getContent();

                // decoding stream data back into image Bitmap that android understands
                bitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.reset();
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (Exception e) {

        Log.e("ImageDownloader", "Something went wrong while" +
                " retrieving bitmap from " + url + e.toString());
    }
    return bitmap;
}`

我想在我的功能中使用Picasso库或Universal Image Loader。有没有办法让这些图书馆使用网址返回带有位图的juste?

谢谢

1 个答案:

答案 0 :(得分:4)

本网站已经回答了这两个问题。

使用毕加索:

private Target mTarget = new Target() {
      @Override
      public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
          // Do whatever you want with the Bitmap
      }

      @Override
      public void onBitmapFailed(Drawable errorDrawable) {
      }

      @Override
      public void onPrepareLoad(Drawable placeHolderDrawable) {
      }
}

...

Picasso.with(this).load("url").into(mTarget);

至少只要请求正在进行,您就必须保留对Target实例的引用。您可以稍后致电cancelRequest()取消加载。

使用UIL:

imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() {
    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
         // Do whatever you want with the Bitmap
    }
});