Code an Image Gallery Android App With Picasso (P1)

Tram Ho

Picasso is a very popular photo gallery on Android. In this article, we will learn how to use it to handle your image downloading needs.

1. Introduction to Picasso

Picasso (name inspired by famous French artist Pablo Picasso) is a very popular open source Android library for downloading images in your Android application. According to official documents, it says:

… Picasso allows loading images easily in your application with just one line of code!

Note that Picasso uses OkHttp (network library from the same developer) in the background to download images over the internet.

2. Why use Picsso?

When you want to load and display images on your own in Java or Kotlil, you may encounter problems: you have to take care of caching, decoding, network connection management, streaming, external processing rate and more. Picasso is an easy-to-use, well-planned, well-documented and well-tested library that can save you a lot of valuable time and help you with headaches.

Here are many common pitfalls of downloading photos on Android handled by Picasso for you, according to the official documents:

  • Processing aborted ImageView and cancel download in the adapter
  • Transform complex images with minimal memory usage
  • Automatic memory and cache

Adding images to your application can bring your Android application to life. So in this tutorial, we will learn about Picasso 2 by building a simple photo gallery application. It will download images over the internet and display them as thumbnails in RecyclerView and when the user clicks on the image, it will open a detailed operation containing the larger image.

3 Configuration

After creating a new project, specify the following dependencies in your build.gradle. At the time of writing, the latest version of Picasso is 2,71828.

Or with Maven

Add permission to allow freer connection

4 Create an interface

We will start by creating our RecyclerView inside the Activity_main.xml layout file.

Create custom section layouts

Next, create the XML layout (item_image.xml) that will be used for each item (ImageView) in the RecyclerView.

Now that we have created the necessary layouts for our simple library application, the next step is to create the RecyclerView adapter to display the data. However, before we do that, let’s create a simple data model.

5. Create data model

We will define a simple data model for our RecyclerView. This model implements Parcelable to transport high performance data from one component to another in Android. In our case, the data will be transferred from SunsetGalleryActivity to SunsetPhotoActivity.

Note that this SunsetPhoto model only has a single field called url (for demo purposes), but you can have more if you like. This class implements Parcelable, which means we have to override some methods. We can use Android Studio IDEA to create these methods for us, but the downside of this is maintenance. How? Whenever we add any new fields to this class, we may forget to explicitly update the constructor and writeToParcel methods, which can lead to some errors if we don’t update the methods. . Now, to avoid updating or writing these boilerplate methods, Kotlin 1.1.14 has introduced the @Parcelize annotation. This annotation will help us automatically create writeToParcel, writeFromParcel and descriptionContents methods.

Now, our SunsetPhoto class is just two lines! Great!

Remember to add the following code to your application module build.gradle

Also, I’ve included a companion object (or static method in Java) getSunsetPhotos () in the SunsetPhoto model class, which simply returns an ArrayList of SunsetPhoto when called.

8. Create Adapter

We will create a converter to fill our RecyclerView data. We will also deploy a click listener to open the detailed activity, Sunset SunsetPhotoActivity, through which is an example of SunsetPhoto as an additional purpose. The detailed operation will show close-up of the image. We will create it in the following section. ) {

} Note that we have used the extension function applied to place an object that is added on purpose. As a reminder, the applicable function returns the object passed to it as an argument (that is, the recipient object).

9. Download the image from the URL

We will need Picasso to do our work in this section not to draw us a work of art, but to take photos from the internet and display them. We will display these images individually in their respective ImageViews inside our RecyclerView onBindViewHolder () method when the user scrolls the application.

The get () method returns a single Picasso instance, initialized with the following default configurations:

  • LRU memory cache 15% of application RAM available.
  • The cache of 2% storage capacity up to 50MB but not less than 5 MB. Note: this is only available on API 14+.
  • Three download themes for disk and network access.

Note that if these settings do not meet the requirements of your application, you are free to build your own version of Picasso with full control of these configurations using Picasso.Builder.

Finally, you call the build () method to return you a Picasso instance with your own configuration.

We recommend doing this in Application.onCreate and then putting it as a single object with Picasso.setSingletonInstance in that method to ensure that the Picasso object is a global object.

The load () starts an image request using the specified path. This path can be a remote URL, a file resource, a content resource, or an Android resource.

Placehodel (int placeholderResId) method : The local or drawable placeholder resource id is used while the image is being loaded and then displayed. It serves as a good user experience to display placeholder images while images are downloading.

Note that Picasso first checks if the requested image is in the cache and if so, it displays the image from there (we’ll discuss more about caching in Picasso later in the following section. ). Other methods

  • error (int errorResId) : can be used if the requested image cannot be loaded because the site may crash.
  • noFade (): Picasso always fades in the image to be displayed in ImageView. If you don’t want this fading animation, just call the noFade () method.
  • into (ImageView imageView) : the target image view where the image will be placed.

Resize images and convert

If the server you are requesting images from doesn’t provide you with the images you need at the requested size, you can easily resize them by resizing (int targetWidth, int targetHeight). Calling this method will resize the image and then display it on ImageView. Note that the size is in pixels (px), not dp.

You can pass Android size resources for both width and height using the resizeDimen (int targetWidthResId, int targetHeightResId) methods. This method converts the size into raw pixels and then calls resize () in the hood hood to convert the converted dimensions (in pixels) as arguments.

Note that these resizing methods will not respect the aspect ratio. In other words, the aspect ratio of your image may be distorted.

Fortunately, Picasso provides us with some useful methods to solve this problem:

  • centreCrop () : scales the image evenly (maintains the aspect ratio of the image) so that the image fills a given area, with as many images as possible displayed. If necessary, the image will be cropped horizontally or vertically to fit. Calling this method cuts an image within the specified limits by resizing ().
  • centreInside (): Scale the image so that both sizes are equal to or smaller than the required limit. This will center an image inside the bounds specified by resizing ().
  • o nlyScaleDown () : only resizes the image if the original image size is larger than the destination size specified by the resize ().
  • fit () : try to resize the image to fit exactly within the limits of the target ImageView.

Image Rotation

Picasso has an easy API to rotate an image and then display that image. The rotation method (float) rotates the image according to the specified degrees.

In the example above, this will rotate the image 90 degrees. The mode of rotation (float, pivot, pivot) rotates the image in the specified degrees around the pivot point.

Transformation

In addition to manipulating an image by rotating it, Picasso also gives us the option to apply a custom transformation to an image before displaying it.

You just need to create a layer that implements the Picasso Transform interface. You must then override the two methods:

Bitmap transform(Bitmap source) : this transforms the source bitmap into a new bitmap.

String key(): returns a unique key for conversion, which is used for storage purposes.

Here, I applied a circular crop transformation to images from the open source Picasso Transformations Android library. This library has many variations that you can apply to an image with Picasso, including transforms to blur or shrink the gray of an image. Check to see if you want to apply some interesting transformations to your image.

Share the news now

Source : Viblo