The Wayback Machine - https://web.archive.org/web/20240930173444/https://www.geeksforgeeks.org/how-to-use-picasso-image-loader-library-in-android/
Open In App

How to Use Picasso Image Loader Library in Android?

Last Updated : 19 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Picasso is open source and one of the widely used image download libraries in Android. It is created and maintained by Square. It is among the powerful image download and caching library for Android. Picasso simplifies the process of loading images from external URLs and displays them on your application. For example, downloading an image from the server is one of the most common tasks in any application. And it needs quite a larger amount of code to achieve this via android networking API. By using Picasso, you can achieve this with a few lines of code. 

How to Use Picasso Android Library?

Step 1: Create an empty activity project

Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project. Note that select Java as the programming language.

Step 2: Adding the required dependency to app-level gradle file

For using Picasso in the android project, we have to add a dependency in the app-level gradle file. So, For adding dependency open app/build.gradle file in the app folder in your Android project and add the following lines inside it. Add these lines inside dependencies{}.

implementation ‘com.squareup.picasso:picasso:2.8’ 

Refer to the following image, if unable to locate the app-level gradle file and invoke the dependency.

Now click on the “Sync Now” button. So that the Android Studio downloads the required dependency files. If you get any type of error then you may check the error on stackoverflow.

Step 3: Working with the Manifest File

Now add InternetPermission inside the AndroidManifest.xml file. Open the manifest.xml file and add the following line. 

<users-permission android:name=”android.permission.INTERNET”/>

Step 4: Working with the activity_main.xml file

Open the layout file for the activity_main.xml file. We need to add an ImageView to the application’s main layout.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    tools:context=".MainActivity">
  
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:padding="16dp" />
  
</RelativeLayout>


Step 5: Working with the MainActivity.java file

Now Navigate to the MainActivity.java file and add the following block of code. In the first line, we are getting the ImageView instance from the layout. And then load the image from the remote URL mentioned in the JAVA code using the Picasso library.

Java




import androidx.appcompat.app.AppCompatActivity;
  
import android.os.Bundle;
import android.widget.ImageView;
  
import com.squareup.picasso.Picasso;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        ImageView imageView = findViewById(R.id.imageView);
        Picasso.with(this)
                .into(imageView);
    }
}


Output:

Note: Make sure the mobile device or Android Emulator has the network connectivity to load the image.

More Functionalities of the Picasso Library

For any real-time application, we must think of all possible cases. In the above code, we just download the image from the server link. But how to display that image in the app.How to resize it and what if the image loading failed? We need to have another image showing an error message that image loading failed. This all matters for an app developer. The following code changes are made in the MainActivity.java file.

1) Resize

Here we are using Picasso to fetch a remote image and resize it before displaying it in an ImageView.

Java




import androidx.appcompat.app.AppCompatActivity;
  
import android.os.Bundle;
import android.widget.ImageView;
  
import com.squareup.picasso.Picasso;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        ImageView imageView = findViewById(R.id.imageView);
        Picasso.with(this)
                .resize(300, 300)
                .into(imageView);
    }
}


Output:

2) Placeholder 

If your application relies on remote assets, then it’s important to add a fallback in the form of a placeholder image. The placeholder image is shown immediately and replaced by the remote image when Picasso has finished fetching it.

Java




import androidx.appcompat.app.AppCompatActivity;
  
import android.os.Bundle;
import android.widget.ImageView;
  
import com.squareup.picasso.Picasso;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        ImageView imageView = findViewById(R.id.imageView);
        Picasso.with(this)
                .placeholder(R.mipmap.ic_launcher)
                .into(imageView);
    }
}


Output:

3) Error Fallback 

  • Picasso supports two types of placeholder images. We already saw how the placeholder method works, but there’s also an error method that accepts a placeholder image. Picasso will try to download the remote image three times and display the error placeholder image if it was unable to fetch the remote asset.
  • The error image will be shown, in this case when there is no internet connectivity for the application. Instead of loading the image from the URL, the Picasso library shows the error image.

Note: To see this result uninstall the previously loaded application and then install the fresh version of the application from the Android Studio.

Java




import androidx.appcompat.app.AppCompatActivity;
  
import android.os.Bundle;
import android.widget.ImageView;
  
import com.squareup.picasso.Picasso;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        ImageView imageView = findViewById(R.id.imageView);
        Picasso.with(this)
                .error(R.drawable.error_gfg)
                .into(imageView);
    }
}


Output:

4) Cropping 

If you are not sure about the size of the image loaded from the remote server that what will be the size of the image. So in this code snippet image will make the image center cropped.

Java




import androidx.appcompat.app.AppCompatActivity;
  
import android.os.Bundle;
import android.widget.ImageView;
  
import com.squareup.picasso.Picasso;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        ImageView imageView = findViewById(R.id.imageView);
        Picasso.with(this)
                .load("https://media.geeksforgeeks.org/wp-content/uploads/20210101144014/gfglogo-300x300.png") // Equivalent of what ends up in onBitmapLoaded
                .placeholder(R.mipmap.ic_launcher)
                .error(R.drawable.error_gfg)
                .centerCrop()
                .fit()
                .into(imageView);
    }
}


Output:

Troubleshooting while loading an image using Picasso Library

OutOfMemoryError Loading Errors 

If an image or set of images aren’t loading, make sure to check the Android monitor log in Android Studio. There’s a good chance you might see a java.lang.OutOfMemoryError “Failed to allocate a […] byte allocation with […] free bytes” or an Out of memory on a 51121168-byte allocation. This is quite common and means that you are loading one or more large images that have not been properly resized. 

First, you have to find which image(s) being loaded are likely causing this error. For any given Picasso call, we can fix this by one or more of the following approaches: 

  1. Add an explicit width or height to the ImageView by setting layout_width=500dp in the layout file and then be sure to call fit() during your load: Picasso.with(…).load(imageUri).fit().into(…)
  2. Open up your static placeholder or error images and make sure their dimensions are relatively small (< 500px width). If not, resize those static images and save them back to your project.
  3. Try removing android:adjustViewBounds=”true” from your ImageView if present and if you are calling .fit() rather than using .resize(width, height)
  4. Call .resize(width, height) during the Picasso load and explicitly set a width or height for the image such as: 
    Picasso.with(…).load(imageUri).resize(500, 0).into(…). By passing 0, the correct height is automatically calculated.


Previous Article
Next Article

Similar Reads

How to Use Glide Image Loader Library in Android Apps?
Glide, like Picasso, can load and display images from many sources, while also taking care of caching and keeping a low memory impact when doing image manipulations. Official Google apps (like the app for Google I/O 2015) are using Glide. In this article, we're going to explore the functionalities of Glide and why it's superior in certain aspects.
4 min read
Image processing with Scikit-image in Python
scikit-image is an image processing Python package that works with NumPy arrays which is a collection of algorithms for image processing. Let's discuss how to deal with images in set of information and its application in the real world. Important features of scikit-image : Simple and efficient tools for image processing and computer vision techniqu
2 min read
RSA Algorithm using Multiple Precision Arithmetic Library
Public Key Cryptography is also known as Asymmetric Cryptography is the type of cryptography which involves the usage of two keys namely Public Key and Private Key. The Public Key of the receiver is used to encrypt the plaintext by the sender while the Private Key of the receiver is used to decrypt the encrypted message and hence can be decrypted o
4 min read
Information Technology Infrastructure Library (ITIL)
Information Technology Infrastructure Library (ITIL) is provided with a framework of best practices for delivering IT services. The ITIL is an appropriate method to management of IT service and also management can help businesses manage risk, strengthen customer relations, establish cost-effective practices, and build a stable IT environment that p
3 min read
Tokenization Using Spacy library
Before moving to the explanation of tokenization, let's first discuss what is Spacy. Spacy is a library that comes under NLP (Natural Language Processing). It is an object-oriented Library that is used to deal with pre-processing of text, and sentences, and to extract information from the text using modules and functions. Tokenization is the proces
3 min read
Software Framework vs Library
Many of us will be unaware of this difference which is really important to understand during development. The possible answer to this question, if asked, will be "Framework is a collection of various libraries". However, this definition is not entirely true. "Who calls whom" i.e. the caller/callee relationship defines the difference between the two
4 min read
C Library math.h Functions
The math.h header defines various C mathematical functions and one macro. All the functions available in this library take double as an argument and return double as the result. Let us discuss some important C math functions one by one. C Math Functions1. double ceil (double x) The C library function double ceil (double x) returns the smallest inte
6 min read
<strings> library in C++ STL
Member functions String.constructor : Construct string object (public member function ).String.destructor : String destructor (public member function )String.operator= : String assignment (public member function ) Iterators Begin : Return iterator to beginning (public member function )End : Return iterator to end (public member function )Advance :
3 min read
Containers in C++ STL (Standard Template Library)
A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference ob
2 min read
<numeric> library in C++ STL
Common mathematical functions std::fabs: This function returns the absolute value. std::sqrt: This function returns the square root std::sin: This function returns the sine measured in radians. Special mathematical functions std::beta: This function evaluates the (complete) Beta integral with given parameters std::hermite: This function Returns the
2 min read
<regex> library in C++ STL
Main classes These classes encapsulate a regular expression and the results of matching a regular expression within a target sequence of characters. basic_regex: Regular expression object (class template) sub_match: Identifies the sequence of characters matched by a sub-expression (class template) match_results: Identifies one regular expression ma
2 min read
Program for triangular pattern (mirror image around 0)
Given the value of n, print the pattern.Examples : Input : n = 5 Output : 0 101 21012 3210123 432101234 Input : n = 7 Output : 0 101 21012 3210123 432101234 54321012345 6543210123456 Below is the program to print the above pattern C/C++ Code // C++ Implementation to print the pattern #include <bits/stdc++.h> using namespace std; // Function d
5 min read
Image Steganography in Cryptography
The word Steganography is derived from two Greek words- 'stegos' meaning 'to cover' and 'grayfia', meaning 'writing', thus translating to 'covered writing', or 'hidden writing'. Steganography is a method of hiding secret data, by embedding it into an audio, video, image, or text file. It is one of the methods employed to protect secret or sensitive
8 min read
Backing up Cisco IOS Router image
As a network administrator, you should always have a backup for worse conditions. One of the common worse conditions that can occur is the IOS image of a device being deleted. This condition gets worse if there is no backup of the IOS image present. So to ignore conditions like these, a backup should be a must and here we will take a Cisco IOS imag
4 min read
Components of Image Processing System
Image Processing System is the combination of the different elements involved in the digital image processing. Digital image processing is the processing of an image by means of a digital computer. Digital image processing uses different computer algorithms to perform image processing on the digital images. It consists of following components:- Ima
2 min read
OpenCV | Hands on Image Brightness
Brightness means to change the value of each and every image pixel. This change can be done by either increasing or decreasing the pixel values of the image, by any constant. This article gives an in-depth knowledge about how can an image brightness be changed using OpenCV. Input : Original Image Output : -> Original Image -> Image with brigh
3 min read
Displaying the coordinates of the points clicked on the image using Python-OpenCV
OpenCV helps us to control and manage different types of mouse events and gives us the flexibility to operate them. There are many types of mouse events. These events can be displayed by running the following code segment : import cv2 [print(i) for i in dir(cv2) if 'EVENT' in i] Output : EVENT_FLAG_ALTKEY EVENT_FLAG_CTRLKEY EVENT_FLAG_LBUTTON EVENT
3 min read
Convert an image into jpg format using Pillow in Python
Let us see how to convert an image into jpg format in Python. The size of png is larger when compared to jpg format. We also know that some applications might ask for images of smaller sizes. Hence conversion from png(larger ) to jpg(smaller) is needed. For this task we will be using the Image.convert() method of the Pillow module. Algorithm : Impo
2 min read
Convert Image into Sketch
In Python, an image is just a two-dimensional array of integers. So one can do a couple of matrix manipulations using various python modules in order to get some very interesting effects. In order to convert the normal image to a sketch, we will change its original RGB values and assign its RGB values similar to grey, in this way a sketch of the in
3 min read
Performance metrics for image steganography
Overview :Various methods are used to evaluate the quality of image steganography. Each of these methods assesses a different aspect of the result obtained after steganography. Some of the well-known methods are Mean Square Error(MSE), Peak Signal to Noise Ratio(PSNR), Structured Similarity Index Measure(SSIM), Payload Capacity. Payload capacity :
2 min read
Python Program to detect the edges of an image using OpenCV | Sobel edge detection method
The following program detects the edges of frames in a livestream video content. The code will only compile in linux environment. Make sure that openCV is installed in your system before you run the program.Steps to download the requirements below: Run the following command on your terminal to install it from the Ubuntu or Debian repository. sudo a
4 min read
Image Manipulation Using Quadtrees
Quadtrees are an effective method to store and locate data of points in a two-dimensional plane. Another effective use of quadtrees is in the field of image manipulation. Unlike in storage of points, in image manipulation we get a complete quadtree with the leaf nodes consisting of individual pixels of the image. Due to this, we can utilize an arra
7 min read
SunPy | Plotting a Solar Image in Python
SunPy is a package for solar data analysis using Python. We will be using this package for analysis of solar data Installation On the command line type: pip install sunpy Downloading Sample Data The SunPy package contains a number of data files which are solar data of proton/electron fluxes from various solar observatory and solar labs. They are st
3 min read
Java | Converting an Image into Grayscale using cvtColor()
To convert a color image to Grayscale image using OpenCV, we read the image into BufferedImage and convert it into Mat Object. Syntax:File input = new File("digital_image_processing.jpg");BufferedImage image = ImageIO.read(input); To transform the image from RGB to Grayscale format by using method cvtColor() in the Imgproc class. Syntax: Imgproc.cv
1 min read
Image Processing
'Recent Articles' on Image ProcessingImage Processing | JavaOpenCV | C++OpenGL | MATLABProject Ideas Image Processing | Java : Image Processing in Java | Set 1 (Read and Write)Image Processing In Java | Set 2 (Get and set Pixels)Image Processing in Java | Set 3 (Colored image to greyscale image conversion)Image Processing in Java | Set 4 (Colored i
2 min read
Image Splicing | Set 1 (Introduction)
Image Forgery can be largely divided into two sub categories: (1) Copy Move Forgery (2) Image Splicing Copy Move Forgery Copy Move forgery is a process of making a composite picture by cutting some object from image and adding it to the same image. Image Splicing Image Splicing is a process of making a composite picture by cutting some object from
1 min read
Notifications in Android Oreo (8+)
Android Oreo has brought in a ton of changes. This also includes the way in which a user issue notifications in an app. In this article, we will discuss the changes required to be made in the notification department. The following things are to be kept in mind while issuing notifications: Designing a Notification ChannelImportance of each notificat
3 min read
Android | 8.0 Oreo
8.0 Oreo is the 8th major update and the fifteenth version of the Android operating system. It was first released as an alpha quality developer preview in March 2017 and released to the public on August 21, 2017. Till date, it is the latest OS but another version called Android P is rolling out soon! More Smarter, faster, and extremely powerful The
3 min read
Google Maps in Android
Maps are of great use and it increases the productivity of an app. Google Maps API allows Android developers to integrate Google Maps in their app. Below is the step-by-step process to integrate Google Maps into Android applications: Goto https://developers.google.com/maps/documentation/android-api/signup and click on "GET STARTED" button as shown
3 min read
Android Boot Process
Booting Process In computing, booting is starting up a computer or computer appliance until it can be used. It can be initiated by hardware such as a button press, or by software command. After the power is switched on the computer is relatively dumb, and can read only part of its storage called Read-only memory. There a small program is stored cal
4 min read
Article Tags :
Practice Tags :