android framework - Glide - a powerful image loading library

Glide 4 - Powerful Image Loading Library

**Introduction:** A powerful image loading library that can load local images, network images, Gifs, and videos.
Glide official website docs: https://muyangmin.github.io/glide-docs-cn/
can be used with transformation effect library: glide-transformations: https://github.com/wasabeef/glide-transformations

**Advantages:**Glide supports pulling, decoding and displaying video snapshots, pictures, and GIF animations. Glide's Api is so flexible that developers can even plug in and replace it with any network stack they like. By default, Glide uses a custom HttpUrlConnection-based stack, but also provides a library of tools for quick integration with Google Volley and Square OkHttp.

use:

1. Add dependent library

repositories {
        jcenter()
        mavenCentral()
    }
 implementation 'com.github.bumptech.glide:glide:4.9.0'
 annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
 implementation 'jp.wasabeef:glide-transformations:4.1.0'
permissions
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

2. General usage method

String url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1566894390240&di=7ed8a09c48bb298d7872a60e80367179&imgtype=0&src=http%3A%2F%2Fimg2.zol.com.cn%2Fproduct%2F103_940x705%2F258%2FceXyT7KxZC9U.jpg";
String gifUrl = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1566894290904&di=3283907b4d74878f5d290d25d6b061f0&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201610%2F10%2F20161010141924_V8vUT.thumb.700_0.gif";

ImageeView imageView = findViewById(R.id.image_view);
LinearLayout linearLayout = findViewById(R.id.linear_layout);
The Activity or Fragment is passed in to Glide.with(), where this is the Activity where Glide is used

1. Ordinary loading pictures-with-load-into

Glide.with(this)
		.load(url)
		.into(imageView);

2. Loading with placeholder image -placeholder()-error()

R.drawable.ic_photo_library和R.drawable.ic_error_outline_black_48dp为自己添加的占位图
RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.drawable.ic_photo_library)
                .error(R.drawable.ic_error_outline_black_48dp);
Glide.with(this)
		.load(url)
		 .apply(requestOptions)
		 .into(imageView);

3. Specify the image size to load -override(w,h)

The GlideUtil class can be encapsulated for easy use
public class GlideUtil {
    public static void load(Context context,
                     String url,
                     ImageView imageView,
                     RequestOptions requestOptions){
        Glide.with(context)
                .load(url)
                .apply(requestOptions)
                .into(imageView);
    }
}

use:

//override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINA)加载原图(非压缩)
//注意:此处的Target是com.bumptech.glide.request.target包下的
 RequestOptions options = new RequestOptions()
                .override(200, 100);//(宽, 高)
 GlideUtil.load(this, url, imageView, options);

4. Cache mechanism - CacheStrategy

By default, Glide checks the following multi-level caches before starting a new image request:

  1. Active Resources - Is there another View currently displaying this image?
  2. Memory cache - Is the image loaded recently and is it still in memory?
  3. Resource type (Resource) - Has this image been decoded, converted, and written to disk cache before?
  4. Data source (Data) - Were the resources used to construct this image previously written to the file cache?
    The first two steps check whether the picture is in memory, and if so, return the picture directly. The last two steps check to see if the image is on disk so that the image is returned quickly but asynchronously.
    If none of the four steps find the image, Glide goes back to the original source to retrieve the data (raw file, Uri, Url, etc.).

Commonly used:
1. new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE);
Call the diskCacheStrategy() method and pass in DiskCacheStrategy.NONE to disable Glide's hard disk caching function.
This diskCacheStrategy() method is basically everything about the Glide hard disk cache function, and it can receive five parameters:
* DiskCacheStrategy.NONE: Indicates that no content is cached.
* DiskCacheStrategy.DATA: Indicates that only original images are cached.
* DiskCacheStrategy.RESOURCE: Indicates that only converted pictures are cached.
* DiskCacheStrategy.ALL : Indicates that both the original image and the converted image are cached.
* DiskCacheStrategy.AUTOMATIC: Indicates to let Glide intelligently choose which cache strategy to use according to the image resource (the default option).
2. Glide automatically turns on the memory cache, and skipMemoryCache is true, which disables the function

        RequestOptions options = new RequestOptions()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE);
        GlideUtil.load(this, url, imageView, options);

5. Specify the loading format - into () automatic identification

The syntax in Glide 3 is first load() and then asXXX().
In Glide 4, it is asXXX() first and then load(), usually directly following with().
The .asBitmap() method allows only static images to be loaded. If it is a gif, the first frame is loaded.
AsGif() is mandatory to load dynamic images.
.asFile(), force the loading of the specified file format.
.asDrawable(), force the loading of Drawable format.

		//R.drawable.ic_photo_library为自己添加的占位图
		RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.ic_photo_library);
        Glide.with(this)
                .load(gifUrl)
                .apply(options)
                .into(imageView);

6-1, callback and monitoring - into () pass Target

For example: into() cannot directly pass in layout objects such as LinearLayout, so create a Taget

SimpleTarget<Drawable> target = new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                //resourse是Glide加载出来的图片对象
                linearLayout.setBackground(resource);
            }
        };
Glide.with(this)
         .load(url)
         .into(target);

6-2. Callback and monitoring - preload() preloading

Preload the picture in advance, and read it directly from the cache when the picture really needs to be loaded

 Glide.with(this)
                .load(url)
                .preload();
Glide.with(this).load(url).into(imageView);

6-3. Callback and monitoring - submit() to download pictures

The submit() method is used to download the original size of the picture, and submit(int width, int height) can specify the size of the downloaded picture. Return the FutureTarget object immediately after the call, and then download the picture in the background. After the download is complete, call the get() method of FutureTarget to get the downloaded picture file. If the picture is not downloaded, the get() method will block the thread, so the new open Thread download.
It is recommended to use the thread pool, please refer to: https://blog.csdn.net/weixin_44565784/article/details/100101695
Steps:
1. Write a tool class (FileUtil.java)
for copying files in advance to save space, the tool class code See step 3 of the article: https://blog.csdn.net/weixin_44565784/article/details/100101695
2. Download pictures

new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = Glide.with(getApplicationContext())
                    							.asFile()
                    							.load(url)
                    							.submit()
                    							.get();
                    File DCIMdir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsoluteFile();
                    if (!DCIMdir.exists()) {
                        DCIMdir.mkdir();
                    }
                    String fileName = System.currentTimeMillis() + ".jpg";
                    File targetFile = new File(DCIMdir, fileName);
                    //将下载的图片文件复制到本地图片文件
                    FileUtil.copyFile(file, targetFile);
                    Snackbar.make(view, "图片已保存。\n" + targetFile.getPath(), Snackbar.LENGTH_SHORT).show();
                    //通知图库更新
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.fromFile(new File(targetFile.getParent()))));
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

6-4. Callback and monitoring -asBitmap() to download pictures

The method is similar to 6-3. It may be that the version is different, so .toByte[] cannot be used, so use Target to accept Bitmap, and then convert to byte[]

SimpleTarget<Bitmap> target = new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                File DCIMdir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsoluteFile();
                if (!DCIMdir.exists()) {
                    DCIMdir.mkdir();
                }
                String fileName = System.currentTimeMillis() + ".jpg";
                File targetFile = new File(DCIMdir, fileName);
				//bitmap 转 byte[] 
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                resource.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                byte[] bytes = outputStream.toByteArray();
                
                FileUtil.copyByBytes(bytes, targetFile);
                Snackbar.make(view, "图片已保存。\n" + targetFile.getPath(), Snackbar.LENGTH_SHORT).show();
                //通知图库更新
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.fromFile(new File(targetFile.getParent()))));
            }
        };
        Glide.with(this)
                .asBitmap()
                .load(url)
                .into(target);
    }

6-5. Callback and monitoring -listener() monitoring status

If true is returned in the onResourceReady() method, then the Target's onResourceReady() method will not be called back.

Glide.with(this)
                .load(url)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(imageView);

7-1. Image transformation-transform

transform(…) method, just pass the image transformation operation you want to perform as a parameter into the transforms() method, which is ready-made package centerCrop, fitCenter, circleCrop

RequestOptions requestOptions = new RequestOptions()
                .circleCrop();
GlideUtil.load(this, url, imageView, requestOptions);

7-2. Image transformation-glide-transformations

Introduce glide-transformations, which implements many common image transformation effects, such as cropping transformation, color transformation, blur transformation, etc.

RequestOptions transform = new RequestOptions()
                .fitCenter()
                .transform(new BlurTransformation());
Glide.with(this)
                .load(url)
                .apply(transform)
                .into(imageView);

8. Custom module-AppGlideModule

Inherit AppGlideModule, rewrite various configurations of Glide, and realize customization
1. Create a new class (MyGlideModule.java), inherit AppGlideModule, add @GlideModule annotation at the beginning, remember to add dependencies...:compiler:..., Rebuild Project can be used GlideApp

@GlideModule
public class MyGlideModule extends AppGlideModule {
    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        builder.setDiskCache(new ExternalPreferredCacheDiskCacheFactory(context));
    }
}

2. Use GlideApp

GlideApp.with(this)
                .load(url)
                .into(imageView);

More introduction: https://www.jianshu.com/p/84932a0eb68b

Note: @GlideModule can be recognized without registration in Glide4
//在Glide4中不需要
  <meta-data
            android:name="完整包名"
            android:value="GlideModule" />

9-1. Using the Generated API

Use the Generated API (before using it, you must have a custom class and add @GlideModule annotations (there is no need to write methods in it) to use GlideApp). Generated API is a new function introduced in Glide 4. Its working principle is to use annotation processor (Annotation Processor) to generate an API. In the Application module, the streaming API can be used to call RequestBuilder, RequestOptions and integration at one time. All options in the library.

//diskCacheStrategy、placeholder在RequestOptions中
        GlideApp.with(this)
                .load(url)
                .circleCrop()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .placeholder(R.drawable.ic_photo_library)
                .into(imageView);

9-2. Using Generated API-custom

With the help of @GlideExtension and @GlideOption, you can create your own API
1. Customize the API class, remember to add annotations

@GlideExtension
public class MyAPI {
    /**
     * 构造函数声明成private
     */
    private MyAPI(){}

    /**
     *方法都必须是静态方法,
     * 而且第一个参数必须是RequestOptions,后面你可以加入任意多个你想自定义的参数
     * @param requestOptions
     */
    @GlideOption
    public static BaseRequestOptions<?> cacheSource(BaseRequestOptions<?> requestOptions){
        return requestOptions.override(400, 400);
    }
}

2. use

//cacheSource()为自定义的API
GlideApp.with(this)
                .load(url)
                .cacheSource()
                .into(imageView);

----------------over---------------

Guess you like

Origin blog.csdn.net/weixin_44565784/article/details/100061097