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

标签 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。这些库有没有办法只返回一个带有 url 的位图?

谢谢

最佳答案

两者都可以,并且都已在本网站上得到解答。

使用 picasso :

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

关于android - 如何使用 Picasso 或 Universal Android Loader 检索位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23462293/

相关文章:

android - seekBar更新Android的MediaPlayer视频时不流畅

android - Kotlin 版本 1.1.4-eap-77 不工作

android - 目前,在中国使用 Android 版谷歌地图是否有效?

c# - 原始像素数组到灰度 BitmapImage

android - 对于同一个位图,位图有时保存为黑色图像

java - SimpleDateFormat 显示错误的本地时间

c++ - Gdiplus::Bitmap::FromHBITMAP 内存泄漏

java - Android 中的位图内存管理

java - ViewPager通用图像加载器如何实现

android - 通用图像加载器