Use of the Picasso framework for obtaining and Displaying Remote images in Android (1 ),

Source: Internet
Author: User

Use of the Picasso framework for obtaining and Displaying Remote images in Android (1 ),

Reprinted please indicate the source: mingsang Android

In Android development, you often need to obtain images remotely and display them on the client. Of course, you can use native HttpUrlConnection and AsyncTask operations, but it is not recommended, in this case, we need not only to write a large amount of code, but also to handle cache and download management. We 'd better encapsulate the code into a library or use a third-party library;

Picasso: A Powerful Image Downloading and Caching Library for Android

According to the name, you will know what it is related to (Picasso: Picasso). Its basic operations are very simple.

This article mainly introduces how to obtain remote images through the Basic HttpUrlConnection and AcyncTask, how to use the Picasso framework, and finally implement a small Demo as an exercise, hope to help those who are learning Android network operations;

1. Use HttpUrlConnection and AsyncTask to download images remotely.

To use HttpUrlConnection and AsyncTask to obtain remote images, take the following steps:

HttpUrlConnection connection = url. openConnection (); // url indicates the image address
InputStream in=connection.getInputStream();
Bitmap bitmap=BitmapFactory.decodeStream(in);
imageView.setBitmap(bitmap)

We know that the above network operations cannot be performed in the main thread, so we need AsyncTask to run the time-consuming operations in the background thread, if you are not familiar with HttpUrlConnection and AsyncTask, refer to the previous article I wrote: HttpUrlConnection HttpClient AsyncTask for Android Network Programming;

The following is an example of using the above Code to download an image:

Public class MainActivity extends Activity {private ImageView imageView; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); imageView = (ImageView) findViewById (R. id. image); String url = "http://www.jycoder.com/json/Image/1.jpg"; // execute the Task new imagedownloadtask(ivbasicimage;.exe cute (url);} // custom get picture Task privat E class ImageDownloadTask extends AsyncTask <String, Void, Bitmap> {ImageView imageView; public ImageDownloadTask (ImageView imageView) {this. imageView = imageView;} protected Bitmap doInBackground (String... addresses) {Bitmap bitmap = null; InputStream in; try {// create a URL Connection URL url = new URL (addresses [0]); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // open the input stream conn. connect (); In = conn. getInputStream (); // encode the input stream bitmap = BitmapFactory. decodeStream (in);} catch (IOException e) {e. printStackTrace ();} finally {if (in! = Null) in. close () ;}return bitmap ;}// after the Task is executed, bitmap @ Override protected void onPostExecute (Bitmap result) {// Set bitmap image for the result imageView is returned. setImageBitmap (result );}}}
2. Picasso framework What is Picasso:

PowerfulImage downloadAndCacheThird-party library; I think this is the most accurate description of it. For other features, refer to the official website: Picasso

How to use Picasso

Android update project-p

Ant jar

2.Basic usage of Picasso:
After adding Picasso to the project, it is very easy to use. You only need a line of code to do this:

Picasso.with(context).load(imageUrl).into(imageView);

A short line of code solves many problems for us:

  • Automatically cache images locally
  • Image compression and conversion to reduce memory consumption
  • The collection of ImageView is automatically processed, that is, the ImageView resources that are not in the field of view are automatically removed;

3.Adapter:The adapter automatically discovers and reuse previously canceled downloads:

    @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);    }

4.Image Format Conversion:Most of the time, you need to convert or crop the image format to save memory or achieve our layout:

Crop size:

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

Custom format conversion:To achieve more effects of image conversion, You can implement a class that implements the Transformation interface and then pass the object to the transform () method:

Public calss myTransformation implements Transformation {@ Overrride public Bitmap transform (Bitmap source) {// implement custom cropping for source} @ Override public String key () {return "square () ";}}

5.Placeholder image:The so-called placeholder image is the default image when the image is not normally displayed. It is set through placeholder (). Picasso also supports setting the default image when the image is incorrectly displayed, and setting through error:

    Picasso.wint(context).load(imageUrl).placeholder(R.drawable.image_placeholder).error(R.drawable.image_error_placeholder).into(imageView);

6.Load local resources:In addition to downloading images over the Internet, Picasso can also load local image resources:

Picasso.with(context).load(R.drawable.icon).into(imageView);    Picasso.with(context).load("file:///android_asset/Adnroid.png").into(imageView);Picasso.wiht(context).load(new File(...)).into(imageView);

7.Debugging:To facilitate debugging, you can callSetIndicatiorEnabled (true); Different colors can be displayed for images from different sources;

The above content is enough, so I will put the Picasso exercise Demo in the next article!

Summary:

Do you think Picasso is easy to use? If the application needs to obtain and display a large amount of image data, why not consider using Picasso. To make a Demo: Android obtains and displays the usage of the remote image Picasso framework (2)

References:

Official Picasso website

Sending and Managing Network Requests

  • Weibo: @ mingsang Android Black History
  • Mailbox: <13141459344@163.com>
  • Personal Homepage: The history of mingsang's victory over Android Wang
  • Public Account: ITBird

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.