Search code examples
androidbitmapuniversal-image-loaderpicasso

How to retrieve Bitmap with Picasso or Universal Android Loader?


Here is my actuel code :

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

I want to do the same in my function but with Picasso library or Universal Image Loader. Is there a way with these librarys to return juste a Bitmap with an url ?

Thank you


Solution

  • Both can and both have already been answered on this site.

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

    You have to keep a reference to the Target instance at least as long as the request is in progress. You can cancel the loading later by calling cancelRequest().

    Using UIL:

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