20Oct

Working with Picasso

by ahmedin Library 0 Comment(s)

In this quick tip, we take a brief look at the popular Android image library, Picasso. It’s a simple and practical library created and maintained by Square. It is great for working with images in your Android projects.

1. Introduction

Picasso is an image library for Android. It’s created and maintained by Square, and caters to image loading and processing. It simplifies the process of displaying images from external locations. In many cases only a few lines of code is required to implement this neat library.

Picasso shines for displaying remote images. The library handles every stage of the process, from the initial HTTP request to the caching of the image. This can be quite verbose when writing code to perform these actions yourself. In this quick tip, we look at a few common use cases.

2. Why use Picasso?

So let’s discuss some of the Pros and cons of Picasso Android Library.
1. To download an Image, all you need to write is these five magical lines.


Picasso.with(mContext)
    .load(movie.getImageUrl())
    .placeholder(R.drawable.ic_placeholder)
    .error(R.drawable.ic_error)
    .into(imageView);

2. No need to create a singleton for image downloading purpose as required for Android Volley.
3. Automatic Handling of Memory and disk caching logic as well.
4. Support for image post processing like resizing and rotation of the downloaded image using simple commands.
5. Support for Request cancellation and parallel downloading.

3. Installation

Start by downloading the JAR file from Picasso’s website. Installing is done the usual manner. If you need help with this step, then take a look at this tutorial by Shane Condor and Lauren Darcey.

If you’re using Android Studio, then you can add it in your build.gradle file in the dependency section.


compile 'com.squareup.picasso:picasso:2.5.2'

4. Hands-On

Step 1: Create a new project

Create a new project in your IDE of choice. Make sure to select a blank Activity if you’re using Android Studio.

Step 2: Image Widget

Open the layout file for the main Activity. We need to add an ImageView to the layout. It doesn’t need to be fancy. The following code snippet shows you what I mean.


<ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

Step 3: Add Picasso

Navigate to the main Activity file. Add the following code block to the onCreate method.


ImageView imageView = (ImageView) findViewById(R.id.imageView);
        Picasso.with(this)
                .load("https://image/working/uri/image.jpg")
                .into(imageView);

In the first line, we get a reference to the ImageView instance in the layout file. We then load an image into the image view using the Picasso library. We first specify the context by calling with and passing in the context. We then call the load method and supply it with the location of the image, a URL in this case. Finally, we tell Picasso where it should display the image when it’s fetched by calling into and pass in the imageView object.

Your IDE will ask you to import the Picasso library. However, to do this manually add the following import statement at the top of the Activity class.


import com.squareup.picasso.Picasso;

Step 4: Permissions

For Picasso to do its work, make sure to add Internet permission to your project’s manifest.


<uses-permission android:name="android.permission.INTERNET"/>

Step 5: Build and Run

That’s pretty much it. If you build and run the application, you should see the image load on the screen.

Features

ADAPTER DOWNLOADS

Adapter re-use is automatically detected and the previous download canceled.


@Override public void getView(int position, View convertView, ViewGroup parent) {
  SquaredImageView view = (SquaredImageView) convertView;
  if (view == null) {
    view = new SquaredImageView(context);
  }
  String url = getItem(position);

  Picasso.with(context).load(url).into(view);
}

IMAGE TRANSFORMATIONS

Transform images to better fit into layouts and to reduce memory size.


Picasso.with(context)
  .load(url)
  .resize(50, 50)
  .centerCrop()
  .into(imageView)

You can also specify custom transformations for more advanced effects.


public class CropSquareTransformation implements Transformation {
  @Override public Bitmap transform(Bitmap source) {
    int size = Math.min(source.getWidth(), source.getHeight());
    int x = (source.getWidth() - size) / 2;
    int y = (source.getHeight() - size) / 2;
    Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
    if (result != source) {
      source.recycle();
    }
    return result;
  }

  @Override public String key() { return "square()"; }
}

Pass an instance of this class to the transform method.

PLACE HOLDERS

Picasso supports both download and error placeholders as optional features.


Picasso.with(context)
    .load(url)
    .placeholder(R.drawable.user_placeholder)
    .error(R.drawable.user_placeholder_error)
    .into(imageView);

A request will be retried three times before the error placeholder is shown.

RESOURCE LOADING

Resources, assets, files, content providers are all supported as image sources.


Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);

DEBUG INDICATORS

For development you can enable the display of a colored ribbon which indicates the image source. Call setIndicatorsEnabled(true) on the Picasso instance.

Sources: 1 | 2

LEAVE A REPLY

Your email address will not be published. Required fields are marked*