Picasso library

Picasso library in Android with Example

Picasso library is a popular image caching and networking library for Android. It is supported by a reliable source, Square, and has several other advantages such as an easy-to-use syntax, and a variety of utilities such as image transformations, filters, and more.

Loading images in Android is difficult because you must deal with network requests, image caching, and image memory. Another significant challenge when caching images is that the image loader must also perform encoding and decoding, which is especially difficult with large images because they are very memory inefficient and require a lot of memory for a single large image. Picasso library is the solution to all of these problems.

In this tutorial, You will learn how to use the Picasso library by creating a simple application.

  • The difference between disk and memory caching.
  • The difference between Picasso library and Glide library.
  • How to apply filters and transformations.
  • How to set placeholders and etc.

Output

Picasso library dependency

 dependencies {

    implementation 'com.squareup.picasso:picasso:2.5.0'
   
}

Picasso library image caching 

Caching is important in Android to ensure that image loading is efficient and that the user has a positive experience. Picasso library employs two caches.
1: Disc Cache
2: Memory Cache 

 Picasso library Image caching
Disk CacheMemory Cache
Disk Cache: If a memory cache is used in the application, the application may be interrupted by a phone call or something else, and the memory cache will be destroyed because it is running in the background. When the application is restarted, it must process each image again, which is where the disc cache comes in handy. When images are no longer available in the memory cache, a disc cache can be used to help reduce loading times and to persist processed Bitmaps. In this case, the background thread checks the disc cache. Memory Cache: It is responsible for storing and retrieving resources from memory. It is faster to write and access, but if you use a memory cache, the application may be interrupted by another task, such as a phone call, and while in the background, the application may be killed and the memory cache destroyed, forcing the application to process each image again when the user resumes. In the UI thread, the Memory Cache is checked. When you load an image, the Picasso library places it in both the disc cache and memory cache. However, if you load a large number of images, the Picasso library will keep the most recent one in-memory cache and attempt to keep all of them in the disc cache. It is important to note that when you load an image, the Picasso library will always attempt to find it in-memory cache first, and If the image is not in the Memory cache, it will attempt to find it in the disc cache. If the image is not in the disc cache, it will have to be loaded from the network.

Difference between Picasso library and Glide library

Point Of DifferencePicasso and Glide
SyntaxIf you just want to load an image, the syntax for both libraries is nearly the same.
Both support fade animation and center cropping, and you can add a placeholder image while loading the image.
Size and Method countThe size of the glide library is nearly 3.5 times larger than the Picasso library.
Picasso library has 849 methods and glide has 2678 methods, if you want to use glide, we must enable ProGuard.
Memory ManagementGlide library uses less memory than Picasso library because it loads the same image based on the size of the view, whereas Picasso library loads the full-size image.
And if you want to avoid the OutOfMemoryError exception, we should use glide.
Image loading timePicasso library uploading time is faster than glide if the file is downloaded from the internet, but glide download time is faster if the file is downloaded from the cache.
When we try to load an image from a URL, both libraries check the local cache first, and if the image is not present in the cache, it will download from the internet because downloading glide will take time to convert and then upload but the Picasso library directly uploading that image by full size.
CachePicasso library downloads the image and stores the full-size image in the cache, and whenever we request the same image, it returns the full-size image and resizes it in real-time to fit into the Image view.
Glide, on the other hand, works differently. It downloads an image from a URL, resizes it to fit the size of the image view, and saves it to the cache. Because if we need an image in two different sizes, glide will store two different copies of the same image in the cache, each with a different resolution. This will increase the size of the disc image.
Animated Gif SupportPicasso library does not support animated gifs, but glide does.
Configuration and CustomizationGlide offers a variety of configuration and customization options.

A simple application using Glide library with a retrofit.

Image Transformation

By- Size:

It is not always possible to request images in perfect dimensions. If your images aren’t the right size, you can use resize(horizontalSize, verticalSize) to change the dimensions to a suitable size or size of your choice. This will allow you to resize the image before it is loaded into ImageView.

Picasso.with(context)
  .load(url)
  .resize(500, 250)
  .into(imageView)

By- ScaleType:

In any image manipulation, resizing an image can distort its aspect ratio and make it look unappealing. When we will load an image view, and you always want to avoid this happening here, Picasso library provides you with two options: centreCrop() and centreInside, Fit.

center Crop()
It is a cropping technique that scales the image so that it crops the extra and fills only the image view’s requested bounds. Even if the entire image is not displayed, the entire image view will be filled.
Picasso.with(context)
       .load(url)
       .resize(500, 250)
       .centerCrop()
       .into(ImageView)
center Inside()
It is a cropping method that scales images so that their dimensions are equal to or less than the bounds of the requested Image view. The image displayed here will be complete but will not fill the entire imageView.
Picasso.with(context)
       .load(url)
       .resize(500, 250)
       .centerInside()
       .into(ImageView)
Fit()
Fit() is a function that internally measures the dimensions of the target ImageView and then uses resize to shrink the picture to fit the target ImageView’s dimensions.
There are two things you must understand about fit (). To begin, invoking fit() may cause an image request to be delayed since Picasso must compute the dimensions of the target image view. Second, fit() can only be used when the target is an ImageView.
Picasso.with(context)
       .load(url)
       .resize(500, 250)
       .fit()
       .into(ImageView)

Placeholder

1: Placeholder()

If you’re using the Picasso library, it may take a long time to load photos from the internet, depending on your user’s environment. The application’s expected behavior is to load a placeholder picture in place of the actual image until the actual image is loaded. Picasso makes it simple to do so using a smooth interface that you just call.

Picasso library will display a placeholder until the actual picture is loaded if you call placeHolder() with a reference to a drawable.

Picasso.with(context)
       .load(url)
       .placeholder(R.drawable.ic_launcher_foreground)
       .into(ImageView)

2: Error PlaceHolder()

When we’re using the Picasso library to load an image into an application and your server goes down. Picasso responds appropriately by providing the option of receiving an error callback.

Picasso.with(context)
       .load(url)
       .placeholder(R.drawable.ic_launcher_foreground)
       .error(R.drawable.ic_launcher_foreground)
       .into(ImageView)

Priority in Image loading

When we need to prioritize the loading of an image in our application, we can use the priority() method provided by the Picasso library. The three constants High, Medium, and Low will be accepted by this procedure priority(). Assigning different priorities has an impact on how pictures load, and by default, all requests have a priority of Medium.

Priority(High)
We should always be able to make the proper Picasso requests. Picasso library allows us to give a higher priority to a large image in our application while giving a lower priority to other images on the same screen.
Picasso.with(context)
       .load(url)
       .priority(Picasso.Priority.HIGH)
       .into(ImageView)
Priority(Medium)
The images are set to Priority Medium by default.
Priority(Low)
Priority Low can be used to assign a low priority to other images on the same screen.
Picasso.with(context)
       .load(url)
       .priority(Picasso.Priority.LOW)
       .into(ImageView)

noFade() and noPlaceholder()

no Fade()
Picasso handled it automatically by fading the image into ImageView to soften the big change in your UI, regardless of whether you are displaying placeholders in place of images in an application. You must call nofade() in Picasso if you do not want the fade effect to appear and want to display the image without any fading. This will summon your image without applying the Fading effect.
Picasso.with(context)
       .load(url)
       .placeholder(R.drawable.ic_launcher_foreground)
       .error(R.drawable.ic_launcher_foreground)
       .noFade()
       .into(ImageView)
no Placeholder()
This has no effect on placeholders that have already been placed. When we construct the new Picasso call, the previous picture clears the ImageView, and the previously set placeholder by .placeholder() is displayed. If the consumer observes quick shifts between images, this may not be a pleasant user experience. It’s therefore preferable to use .noPlaceholder() in the following Picasso call. The preceding image will remain in place until your second image is loaded.
Picasso.with(context)
       .load(url)
       .placeholder(R.drawable.ic_launcher_foreground)
       .error(R.drawable.ic_launcher_foreground)
       .noPlaceholder()
       .into(ImageView)

Image Rotation

Picasso’s library has a feature that allows him to rotate images. There are two possibilities:

Simple Rotation
When we supply it as a parameter, it simply rotates the image by degrees. It is possible to pass a value between 0 and 360 that makes sense. rotate is a simple rotation command (degrees: float)
Picasso.with(context)
       .load(url)
       .rotate(120f)
       .into(ImageView)
Complex Rotation
By default, the rotation center is at 0,0, referred to as the “pivot point.” In some applications, it is necessary to rotate a picture to a specified pivot point that is not the normal center. This is something the Picasso library allows you to accomplish with rotation (degrees: float, pivotX: float, pivotY: float).
Picasso.with(context)
       .load(url)
       .rotate(120f,110f,222f)
       .into(ImageView)

Picasso library Example in Android studio

Step-by-step explanation:

The following is an example of using the Picasso library in Android, in which we will demonstrate various features provided by the Picasso library.

In this case, we’ve used a simple image URL that will be loaded in imageview using the Picasso library.

Step 1: Create a New Project in Android Studio.

Step 2: Open build.gradle(Module: app) and add the following dependency:

  • In this project, we will use the Picasso library for image loading.
 dependencies {

    implementation 'com.squareup.picasso:picasso:2.5.0'
   
}

Step 3: Add internet permission to the AndroidManifest.xml file

  • Because we work with network operations and other such things, we require Internet connection permission.
//internet permission
    <uses-permission android:name="android.permission.INTERNET"/>
  • Below is the code of the AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sagar.picassoexample">

    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.PicassoExample">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Step 4:  In the activity_main.xml layout file, we used one image view, which will be your target imageView and where the image will be displayed.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/ImageView"
        android:layout_width="400dp"
        android:layout_height="400dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 5: In MainActivity.kt file implementing Picasso library with simple image URL.

package com.sagar.picassoexample

import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.squareup.picasso.Picasso

class MainActivity : AppCompatActivity() {
    private lateinit var ImageView: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ImageView = findViewById(R.id.ImageView)
        Picasso.with(this)
            .load("https://i1.wp.com/developersdome.com/wp-content/uploads/2021/08/Blue-and-White-Abstract-Technology-Blog-Banner-2.png?resize=2048%2C1152&ssl=1")
            .error(R.drawable.ic_launcher_foreground).placeholder(R.drawable.ic_launcher_foreground)
// *********************Try it yourself**********************
//            .rotate(120f)
//            .noPlaceholder()
//            .noFade()
//            .priority(Picasso.Priority.LOW)
//***********************************************************                
            .into(ImageView)
    }
}

Run the application now. You will get the output shown in the output section.

We hope that this guide will assist you in quickly creating a simple android Application using the Picasso library in android. We concentrated on making a simple application for this tutorial. If you have any problems, please post them in the comments section, we will gladly assist you.

This Post Has One Comment

Leave a Reply