Detailed explanation of image loading library Glide


1. Preliminary basic knowledge reserve

Now Android's image loading library is very mature, from the earliest old image loading framework UniversalImageLoader (2011), to the later Volley (2013) launched by Google, and then to the emerging army Picasso (2012) and Glide (2013) ), and of course Facebook’s Fresco (2015). Each is very stable and functional. Because the functions implemented are relatively similar, developers can learn one of them.

(PS: The author of UniversalImageLoader is no longer maintained, so it is not recommended for the time being)

At the Google Developer Forum held in Thailand, Google introduced an image loading library called Glide by bumptech. This library is widely used in Google's open source projects, including the official app released at the 2014 Google I/O conference.

Glide is built on the basis of Picasso, so the syntax is similar, but its functions are a little more, such as supporting the loading of GIF animation ; the size of the image loaded by Glide is the size of ImageView, not the full size of Picasso. Picture; Glide's default Bitmap format is RGB_565, which is half the memory overhead of Picasso's ARGB_8888 format (the image loading quality is therefore slightly lower); Glide even supports multimedia loading, such as Video.

Second, the above code, the specific implementation

Step 1: Add dependencies to the build.gradle file;

compile'com.github.bumptech.glide:glide:3.7.0'

The latest version: Glide4 has come out, specific reference: bumptech/glide

Step 2 : Add network permissions to AndroidManifest.xml;

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

> The first and second steps are prerequisites for using Glide, please don't forget.

Step 3 : Start using Glide to load a network image;

(1) Add an ImageView and a Button to the main layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load Image"
        android:onClick="loadImage"/>//Set the button's onClick attribute

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

(2) The loading function of pictures is implemented in MainActivity

public class MainActivity extends AppCompatActivity {

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.image_view);
    }

    public void loadImage(View view) {
        String url = "http://himg2.huanqiu.com/attachment2010/2012/0808/20120808100424609.jpg";
        Glide.with(this).load(url).into(imageView);
    }
}

The running result is shown in the figure:


Using Glide to load images is simpler than using Volley's ImageLoader.

What if it's a Gif? For example, this Hunger Games cousin http://img1.gamedog.cn/2014/05/29/91-1405291103380-50.gif, in fact, the loading method is the same, no need to add additional code, only need to pass in the dynamic The url where the image is located is enough, and Glide will automatically recognize that the Gif animation is loaded.


Next, let's take a closer look at this code that requests a network image:

with() , call the Glide.with() method to create an instance of the loaded image. The with() method can receive parameters of type Context, Activity or Fragment. That is to say, we have a very wide range of choices. Whether we call the with() method in Activity or Fragment, we can directly pass this. This is another advantage of Glide over Picasso, which only accepts context objects.

load() , this method is used to specify the image resource to be loaded. Glide supports loading a variety of image resources, including network images, local images, application resources, binary streams, Uri objects, and more.

into() , specify the ImageView we want to display.

Using Glide to load a picture is based on these three methods, and the rest of the more advanced functions are adding logic between the load() method and the into() method.

Step 4 : Add other commonly used image processing logic in Glide

Specify the placeholder image/image loading failure image ;

Glide.with(this)

     .load(url)

     .placeholder(R.drawable.loading)

     .error(R.drawable.error)

     .into(imageView);

Specify the size of the image. As mentioned earlier, Glide will recognize the size of the ImageView and automatically load the image of the corresponding size, instead of using Bitmap to load, you need to specify the sampling rate of the image yourself. If the developer really needs to specify a size by himself, he can also use the override method of Glide to set it;

Glide.with(this)

     .load(url)

     .override (100, 100)// Glide will load the image to a size of 100*100 pixels

     .into(imageView);

③ To achieve a more powerful image transformation effect - add the glide-transformations library,

Such as cropping transformation, color transformation, shape transformation , etc., very rich.

First, add dependencies to the build.gradle file:

compile'jp.wasabeef:glide-transformations:2.0.2'

        String url="http://himg2.huanqiu.com/attachment2010/2012/0808/20120808100424609.jpg";
        Glide.with(this)
                .load(file)
                //This is to set the image blur
//              .bitmapTransform(new BlurTransformation(this))
                //This is to set the picture blur and the picture black and white at the same time
//              .bitmapTransform(new GrayscaleTransformation(this),new BlurTransformation(this))
                //This is to set the picture to become a circle
//              .bitmapTransform(new CropCircleTransformation(this))
                //This is to set the picture as a rounded rectangle. This setting is a little more complicated, and several types of parameters need to be passed in
                //Parameter types include context, corner radius, image crop ratio, and corner position
//                .bitmapTransform(new RoundedCornersTransformation(this, 48, 0
//                        , RoundedCornersTransformation.CornerType.TOP_LEFT))
				//This is the animation that appears when the image is loaded (our own custom animation)
//                .animate(R.anim.item_alpha_in)
                //This is the animation that appears when the image is loaded (the system defaults, the parameter specifies the duration of the animation)
				.crossFade(2000)
                .into(imageView);

The above code snippets show the settings of some commonly used methods.

The operation effect is as follows:

      

      

The following gif animation is all the animation effects set by the glide-transformations library. Interested readers can go to github to view them directly.

 

Step 5 : Realize the loading of local images

The permissions required for loading local images and requesting network images are different, so you need to add a permission request to the manifest file again.

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

Note: It should be noted here that Android has added runtime permission application requirements since 6.0, and the permission to read local images added here is precisely a sensitive permission, which needs to be dynamically applied at runtime. When running on a 6.0 Android phone , you must apply for dynamic permissions . Below is the application code:

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//Check permission application status
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                        ) != PackageManager.PERMISSION_GRANTED) {//Apply for authorization
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    loadImage();
                }
            }
        });
    

    public void loadImage() {
//        String url = "http://himg2.huanqiu.com/attachment2010/2012/0808/20120808100424609.jpg";
        File file = new File(Environment.getExternalStorageDirectory(), "1524032990849.png");
        Glide.with(this)
                .load(file)
                .crossFade(2000)
                .into(imageView);
    }
    //Processing permission request callback
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    loadImage();
                } else {
                    Toast.makeText(this, "you denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
For more content about the application of runtime permissions, readers are advised to refer to the article "Complete Analysis of Android 6.0 Runtime Permission Processing" by Hongyang Great God , which has a very detailed explanation.


Summary: Glide is relatively simple to use. According to the characteristics of Glide and the comparison with other image loading libraries, the usage scenarios can be drawn:

Need more content representation (such as Gif) ;

Higher performance requirements (cache & loading speed) ;

Professional libraries do professional things. The author once thought that using Volley to network pictures was simple enough.

After using Glide, I know that professional is the fastest.


Welcome, use Glide!


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324650577&siteId=291194637