Android performance optimization - picture optimization (2)

   The loading and display of pictures is an unavoidable problem for every commercial APP. For APPs that rely heavily on pictures, such as wallpaper-based apps and picture-based social apps, the processing of pictures will affect the user experience of the entire APP.

    Before we formally understand how to optimize image-related content in Android, let's take a look at the image formats supported by the Android system.

 1. The format of the picture

    At present, the main image formats natively supported by the mobile Android platform are: JPEG, PNG, GIF, BMP and WebP (supported since Android 4.0), but only three codec formats can be used in Android application development: JPEG, PNG, WebP, and image formats can be determined by viewing the CompressFormat enumeration value of the Bitmap class.

    public enum CompressFormat {
        JPEG    (0),
        PNG     (1),
        WEBP    (2);

        CompressFormat(int nativeInt) {
            this.nativeInt = nativeInt;
        }
        final int nativeInt;
    }

    If you want to use GIF format images at the application layer, you need to introduce a third-party function library for support.

(1)、JPEG

    JPEG is a widely used standard format for lossy compressed images. It does not support transparency and multi-frame animation. Generally, photographic works are ultimately displayed in JPEG format. By controlling the compression ratio, the size of the picture can be adjusted.

(2)、PNG

    PNG is a lossless compressed image format that supports complete transparency channels. In the field of image processing, JPEG has only three channels of RGB, while PNG has four channels of ARGB. Because of the lossless compression, PNG images generally take up a lot of space, which will increase the size of the final APP invisibly. When slimming down, PNG images are generally processed to reduce the size they occupy.

(3)、GIF

    GIF is an ancient image format, which was born in 1987 and became popular with the first generation of the Internet. It features support for multi-frame animation. You are definitely not unfamiliar with this format. Most of the dynamic expressions sent on social platforms are based on GIFs.

(4)、WebP

       Compared with the previous image formats, WebP is a newborn. It was released by Google in 2010. It supports lossy and lossless compression, complete transparency channel, and multi-frame animation. It is an ideal image format. At present, many mainstream APPs in China have applied WebP, such as WeChat, Weibo, Taobao, etc. WebP should be the first choice when it is necessary to ensure the quality of the picture and limit the size of the picture.

2. Compression of pictures

    At present, regardless of the Android platform or the IOS platform, most APPs use PNG format image resources when building the interface. Unless your project already fully supports the WebP format, you will face the requirement of PNG image slimming. Here, we Several tools can be used to compress PNG images to achieve the purpose of slimming.

(1), Lossless compression ImageOptim ( https://imageoptim.com )

    ImageOptim is a lossless compression tool that reduces the space occupied by PNG images without sacrificing image quality by optimizing PNG compression parameters, removing redundant metadata and unnecessary color profiles, etc. Improved loading speed.

(2), lossy compression ImageAlpha ( https://pngmini.com/ )

    ImageAlpha is a lossy PNG compression tool developed by the author of ImageOptim. In comparison, the size of the image is greatly reduced. Of course, the quality of the image will also be affected to a certain extent. The image compressed by this tool needs to be designed The teacher's inspection can be finally launched, otherwise the visual effect of the entire APP may be affected.

(3), lossy compression TinyPNG ( https://tinypng.com/ )

       TinyPNG is also a relatively well-known lossy PNG compression tool. It is provided in the form of a Web site and does not have an independent APP installation package. Like all lossy compression tools, the compressed image needs to be checked by the designer before it can be finally launched. Otherwise, the visual effect of the entire APP may be affected.

   In fact, there are many lossless compression tools, such as JPEGMini ( http://www.jpegmini.com/ ), MozJPEG ( https://imageoptim.com/mozjpeg ), etc. You can choose the one that suits your project. It's about finding a compromise between image size and image quality.

(4) Convert PNG/JPEG to WebP

        If your APP supports at least Android 4.0, you can directly use the capabilities provided by the system to support WebP. If it is a system below 4.0, you can also integrate third-party function libraries such as webp-android-backprot in the APP ( https: //github.com/alexey-pelykh/webp-android-backport/tree/master/webp-android-backport-library ) to implement WebP support. According to Google's test, the lossless compression of WebP is 45% smaller than PNG files, even if these PNG files are compressed by other compression tools such as ImageOptim ( https://imageoptim.com ), WebP can still be reduced by about 28% file size.

        WebP conversion tools can choose Zhitu ( http://zhitu.isux.us/ ) and iSparta ( http://isparta.github.io/ ), etc.;

(5) Try to use PNG images in NinePatch format

    .9.png image format, referred to as NinePatch image, is still a PNG image in essence. It is a special PNG image format for the Android platform, which can stretch or fill the content at the specified position of the image. The advantage of the NinePatch map is that it is small in size, does not deform when stretched, and can be well adapted to various Android models. Android SDK comes with a NinePatch image editing tool, located in sdk/tools/draw9patch, click to start; of course, Android Studio also integrates the function of PNG to NinePatch, we only need to right-click a PNG image that needs to be converted, in In the pop-up dialog box, select Create 9-Patch File... to automatically complete the conversion.

 

3. Cache of pictures

        With the development of Android today, there have been many excellent image cache function libraries. Developers can choose according to the actual needs of the project. There are two levels of cache in the traditional image cache solution, namely memory cache and disk cache. In the Fresco launched by Facebook, it adds a first-level cache, that is, the Native cache, which greatly reduces the probability of OOM for apps using Fresco.

(1)、BitmapFun

        BitmapFun function library is an example of image loading and caching in the official Android tutorial. For simple image loading requirements, using BitmapFun is enough. It was used more in early Android APP development, and later with more and more mature With the emergence of powerful function libraries, BitmapFun has gradually withdrawn from the stage of actual project development. But as a tutorial for getting started with image caching, it still plays a role that cannot be ignored.

(2)、Picasso(https://github.com/square/picasso

    Picasso is one of the many open source projects of the famous Square company, named after the famous painter Picasso, and even the Sample app uses Picasso's famous paintings as examples. In addition to realizing image download and secondary cache functions, it also solves some common problems.

  • Handle Image View recycling and download cancellation as normal in the adapter.
  • Implement complex image transformations with as little memory as possible

    In Picasso, we can download and render images into ImageView with one line of code.

Picasso.with(context).load("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png").into(imageView);

(3)、Glide(https://github.com/bumptech/glide

    Glide is a Google-recommended image loading and caching library for the Android platform. This library is widely used in Google's open source projects. Glide and Picasso have 90% similarity. It can be said that it is a clone version of Picasso, but there are still many differences in details. Glide is optimized to be as smooth as possible for scrolling lists containing images. In addition to static images, Glide also supports the display of GIF format images. Glide provides a flexible API that allows developers to easily replace the network function library used to download images. By default, it uses HttpUrlConnection as the network request module. Developers can also flexibly use Google's Volley or Square according to the actual needs of their projects Function libraries such as OkHttp are replaced.

       The use of Glide can also be done with one line of code. The statement is as follows, which is very similar to Picasso.

Glide.with(this).load("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png").into(imageView);

(4)、Fresh(https://github.com/facebook/fresco

    Fresco is a powerful image loading and caching function library open sourced by Facebook. Compared with other image caching libraries, the most notable feature of Fresco is that it has a three-level cache: two-level memory cache and one-level disk cache. Its main features are as follows.

  • Load JPEG images progressively.
  • Displays GIF and WebP animations.
  • Scalable, customizable image loading and display.
  • On Android 4.x and below systems, the image is placed in a special area of ​​Android memory, which makes the application run more smoothly and greatly reduces the occurrence of OutOfMemoryError errors.
  • Facebook gives the official Chinese API: Fresco Chinese official API

(5)、Android-Universal-Image-Loader(https://github.com/nostra13/Android-Universal-Image-Loader

    Android-Universal-Image-Loader is UIL for short. It is an old image downloading and caching function library on the Android platform. It is powerful, flexible and highly customizable. It provides a series of configuration options and can well control the process of image loading and caching. . There are many users, and the early Android developers should have been in contact with it, and it is still used in many projects. UIL also supports L2 cache, its main features are as follows.

  • Synchronous or asynchronous multi-threaded image loading.
  • Highly customizable: thread pools, downloaders, decoders, memory and disk caching, image display options, and more.
  • The display of each image supports a variety of customization options: default stub images, cache switching, decoding options, Bitmap processing and display, etc.
  • Pictures can be cached in memory or on disk (the device's file system or SD card);
  • The image loading process can be monitored in real time, including the download progress.

    Finally, let's see how much space will be added to the APP if these function libraries are introduced:

It can be seen that there are many dependent libraries of the Fresco function library. Except for the jars of several of his function libraries, the others are required to use Fresco. To sum up, the size of the above function library is as follows:

  • Picasso:118kb
  • Glide : 465kb
  • fresh:770kb
  •  Android-Universal-Image-Loader:159kb

    The selection of the picture function library depends on the specific situation of the APP. For APPs that rely heavily on picture caching, such as wallpapers and picture social APPs, you can choose the most professional Fresco. For general APPs, choosing Fresco will be heavier, after all, Fresco’s 770kb volume is here. According to the needs of APP for image display and caching from low to high, we can sort the above function libraries.

Picasso<Android-Universal-Image-Loader<Glide<Fresco

    It is worth mentioning that if your APP plans to use React Native for the development of some module functions, you need to consider the reuse of the dependent libraries of React Native in the selection of the basic function library, which can reduce the increase in the introduction of React Native. The size of the APP, the function libraries that can be reused are: OkHttp, Fresco, jackson-core.

 

4. Open source code base

Finally, I will share a code base that I have accumulated for a long time, only you can't think of it, there is nothing you can't use, welcome to star

https://github.com/xijiufu

Since the github server is in the United States, access is sometimes very slow, and an open-source Chinese address library is also provided, and the codes of the two warehouses are updated synchronously:

http://git.oschina.net/xijiufu

 

 

Guess you like

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