SoFunction
Updated on 2025-04-09

Three ways to implement image compression in Android

In Android development, image compression is an important optimization method, aiming to improve user experience, reduce network transmission volume, and reduce storage space usage. The following are several mainstream image compression methods, which are analyzed in detail based on principles, usage scenarios and advantages and disadvantages.

1. Mass compression method

Use scenarios

Developers need to reduce file size while maintaining image quality.

What is it

The quality compression method reduces file size by reducing the compression quality of the image (such as the compression rate of JPEG). This method will not change the resolution of the image (width and height remain unchanged), but will reduce the file size of the image.

Why choose it

  • Suitable for scenarios where high image quality is required but reduced file size.
  • Commonly used for image upload in social media applications, ensuring that images are loaded quickly while maintaining good visual effects.

When to use

  • When it is necessary to reduce file size while maintaining image quality.
  • Suitable for network transmission or storage optimization scenarios.

How to implement it

By settingand compress the quality parameters to achieve.

Code example:

//The passed parameter is bitmap
private Bitmap compressImage(Bitmap image) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // The first compression is 100 (not compressed)    (, 100, baos);
    int options = 100;
    // Circular compression until the conditions are met    while (().length / 1024 > 100) {
        ();
        (, options, baos);
        options -= 10;
    }
    // Generate compressed Bitmap    ByteArrayInputStream isBm = new ByteArrayInputStream(());
    return (isBm);
}

Note: Quality compression needs to be adjusted according to personal needs. The example has written 100, but it has not been compressed. You can try compressing to 50, and then compare it with the original image.

Summary of advantages and disadvantages

  • advantage:

    • Simple implementation and small code.
    • It can flexibly control the compression quality, which is suitable for scenarios with high requirements for picture quality.
  • shortcoming:

    • The size occupied in memory remains unchanged (the resolution is not changed), which may lead to large memory consumption.
    • High-quality compression can cause blurry pictures.

2. Sampling rate compression method

user

Developers need scenarios that significantly reduce image size, such as generating thumbnails or adapting to different screen resolutions.

What is it

The sampling rate compression method reduces file size by reducing the resolution of the picture (reducing the number of pixels). By setting, can control the scaling ratio of the picture.

Why choose it

  • It can effectively reduce memory usage and file size.
  • Suitable for scenes where thumbnails are needed to generate or adapt to screen resolutions of different devices.

When to use

  • When a large reduction in image size is required.
  • Suitable for loading large images on devices with limited memory resources.

How to implement it

By settinginSampleSizeto achieve sampling rate compression.

Code example:

//The parameter passed is the path of the picture
private Bitmap getimage(String srcPath) {
     newOpts = new ();
    // Only read the width and height of the picture, and do not load the picture into memory     = true;
    (srcPath, newOpts);
     = false;
    // Calculate the sampling rate according to the requirements    int w = ;
    int h = ;
    float hh = 1280f; // Target height    float ww = 720f; // Target width    int be = 1;
    // Calculate the sampling rate based on width or height    if (w > h && w > ww) {
        be = (int) (w / ww);
    } else if (h > w && h > hh) {
        be = (int) (h / hh);
    }
     = be;
    // Reload the picture    return (srcPath, newOpts);
}

Summary of advantages and disadvantages

  • advantage:

    • It can significantly reduce memory usage and file size.
    • Supports flexible scaling settings.
  • shortcoming:

    • May cause blurry pictures (especially high resolution pictures).
    • The sampling rate needs to be calculated manually, which increases the development complexity.

3. Scaling method

user

Developers need to precisely control the scenes of image size, such as generating thumbnails of specific scales.

What is it

The zoom method reduces file size by adjusting the size of the picture (scaling width height). pass()andCanvasDrawing the scaled picture can achieve size compression.

Why choose it

  • Suitable for scenes where precise image size is required.
  • Ability to generate thumbnails or adaptive images that meet a certain scale.

When to use

  • When it is necessary to generate thumbnails of specific sizes or adapt to screens of different devices.
  • Suitable for scenes where precise control of the image proportions is required.

How to implement it

By creatingCanvasandMatrixPerform scaling.

Code example:

//The passed parameter is bitmpa, and there is also a path to save the file.

public static void compressBitmapToFile(Bitmap bmp, File file) {
    int ratio = 2; // Scaling    // Create a zoomed Bitmap    Bitmap result = (() / ratio, 
                                       () / ratio, 
                                       .ARGB_8888);
    Canvas canvas = new Canvas(result);
    Rect rect = new Rect(0, 0, () / ratio, () / ratio);
    (bmp, null, rect, null);

    // Compress and save to file    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    (, 100, baos);
    try {
        FileOutputStream fos = new FileOutputStream(file);
        (());
        ();
        ();
    } catch (Exception e) {
        ();
    }
}

Note: In the above example method, you can directly remove the relevant logic of the file and return result.

public static Bitmap compressBitmap(Bitmap bmp) {
    int ratio = 2; // Scaling    // Create a zoomed Bitmap    Bitmap result = (
        () / ratio, 
        () / ratio, 
        .ARGB_8888
    );
    Canvas canvas = new Canvas(result);
    Rect rect = new Rect(0, 0, () / ratio, () / ratio);
    (bmp, null, rect, null);
    return result; // Directly return to the scaled Bitmap}

Summary of advantages and disadvantages

  • advantage:

    • Supports precise control of scaling.
    • Suitable for generating pictures that are adapted to different devices.
  • shortcoming:

    • Multiple scaling may cause image distortion.
    • The implementation is relatively complex and requires more code volume.

4. Comparison and summary of the advantages and disadvantages of methods

Method Type advantage shortcoming
Mass compression method - Keep pictures of high quality
- Simple implementation
- Memory usage remains unchanged
- High compression rates can lead to blur
Sampling rate compression method - Significantly reduce file size and memory usage
- Support flexible setting of sampling rate
- May cause blurry pictures
- Manual calculation of the sampling rate is required
Scaling method - Accurate control of image size
- Suitable for generating adaptive images or thumbnails
- Multiple scaling may cause distortion
- Relatively complex implementation

5. Summary of applicable scenarios

  • Mass compression method: Suitable for scenarios where high image quality is needed but reduced file size, such as social media image uploads.
  • Sampling rate compression method: Suitable for scenes where thumbnails are needed to generate or adapt to different screen resolutions, such as loading large images in album applications.
  • Scaling method: Suitable for scenes where precise control of image sizes is required, such as generating thumbnails of specific scales.

By combining the above methods, the appropriate compression strategy can be selected according to specific needs, thereby optimizing the performance and user experience of Android applications.

The above is the detailed content of the three implementation methods of image compression in Android. For more information about Android image compression, please follow my other related articles!