SoFunction
Updated on 2025-04-09

Android development realizes image size and quality compression and saving

There are four attributes for pictures in Android

ALPHA_8: Each pixel occupies 1 byte of memory

ARGB_4444: Each pixel takes up 2byte memory

ARGB_8888: Each pixel takes up 4byte memory (default)

RGB_565: Each pixel takes up 2byte memory

The default color mode for Android is ARGB_8888. This color mode has the most delicate colors and the highest display quality. But again, the memory consumes the most. So use RGB_565 when the effect on the picture is not particularly high (565 has no transparency attribute)

Currently commonly used image formats on Android

There are png, jpeg and webp

png: Lossless compressed image format, supports Alpha channel, Android image cutting materials mostly use this format

jpeg: Lossy compressed image format, does not support transparent background, is suitable for rich colors such as photos (large image compression, not suitable for logo)

webp: is an image format that provides both lossy compression and lossless compression, derived from the video encoding format VP8. From the official Google website, lossless webp is 26% smaller than png, lossy webp is 25%~34% smaller than jpeg. Lossless webp supports Alpha channel, lossy webp is also supported under certain conditions. Lossy webp is supported after Android 4.0 (API 14), lossless and transparent are supported after Android 4.3 (API 18).

use

Size compression

private Bitmap getimage(String srcPath) {  
         newOpts = new ();  
        //Start read the picture, and then set it back to true         = true;  
        Bitmap bitmap = (srcPath,newOpts);//Return bm to empty         = false;  
        int w = ;  
        int h = ;  
        //There are more common mainstream mobile phones with resolutions of 800*480, so we set the height and width to        float hh = 800f;//The height is set to 800f        float ww = 480f;//The width is set to 480f        //Scaling ratio.  Since it is fixed proportional scaling, only one of the data of height or width can be calculated        int be = 1;//be=1 means no scaling        if (w > h && w > ww) {// If the width is large, scale it according to the width fixed size            be = (int) ( / ww);  
        } else if (w < h && h > hh) {// If the height is high, it will be scaled according to the width.            be = (int) ( / hh);  
        }  
        if (be <= 0)  
            be = 1;  
         = be;//Set the scaling ratio        //Read the picture again, note that it has been set back to false at this time        bitmap = (srcPath, newOpts);  
        return compressImage(bitmap);//After compressing the proportion, then perform mass compression    }

Mass compression

Notice:

Before the second compression, you must clear (); then compress

(, quality, baos);

Sometimes we use mass compression without effect, it is possible that the mass of each compression is too small, so we can try to modify the compression quality (quality) to be 10;

Quality compressor prompts, 0-100.0 means compression size, 100 means maximum quality compression. Some formats, such as lossless PNG, will ignore the quality settings;

private Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        (, 100, baos);
        int options = 90;
        int length = ().length / 1024;
        if (length>5000){
            //Reset baos means clear baos            ();
            // Quality compression method, here 100 means no compression, store the compressed data in baos            (, 10, baos);
        }else if (length>4000){
            ();
            (, 20, baos);
        }else if (length>3000){
            ();
            (, 50, baos);
        }else if (length>2000){
            ();
            (, 70, baos);
        }
        //Cyclically determine whether the image is greater than 1M after compression, and it is greater than continue compression        while (().length / 1024>1024) {
            //Reset baos means clear baos            ();
            //The compressed options% here, and the compressed data is stored in baos            (, options, baos);
            //Reduce by 10 each time            options -= 10;
        }
        //Storage the compressed data baos in ByteArrayInputStream        ByteArrayInputStream isBm = new ByteArrayInputStream(());
        //Create the ByteArrayInputStream data to generate pictures        Bitmap bitmap = (isBm, null, null);
        return bitmap;
    }

Mixed compression

private Bitmap comp(Bitmap image) {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();         
    (, 100, baos);  
    if( ().length / 1024>1024) {//Judge if the image is greater than 1M, compress it to avoid overflowing when generating the image ()        ();//Reset baos means clear baos        (, 50, baos);//Create 50% here, store the compressed data in baos    }  
    ByteArrayInputStream isBm = new ByteArrayInputStream(());  
     newOpts = new ();  
    //Start read the picture, and then set it back to true     = true;  
    Bitmap bitmap = (isBm, null, newOpts);  
     = false;  
    int w = ;  
    int h = ;  
    //There are more common mainstream mobile phones with resolutions of 800*480, so we set the height and width to    float hh = 800f;//The height is set to 800f    float ww = 480f;//The width is set to 480f    //Scaling ratio.  Since it is fixed proportional scaling, only one of the data of height or width can be calculated    int be = 1;//be=1 means no scaling    if (w > h && w > ww) {// If the width is large, scale it according to the width fixed size        be = (int) ( / ww);  
    } else if (w < h && h > hh) {// If the height is high, it will be scaled according to the width.        be = (int) ( / hh);  
    }  
    if (be <= 0)  
        be = 1;  
     = be;//Set the scaling ratio    //Read the picture again, note that it has been set back to false at this time    isBm = new ByteArrayInputStream(());  
    bitmap = (isBm, null, newOpts);  
    return compressImage(bitmap);//After compressing the proportion, then perform mass compression}

Sample rate compression

Sampling rate compression is to reduce the resolution of the picture through setting, thereby reducing the disk space and memory size occupied by the picture.

Setting inSampleSize will cause the compressed image to be 1/inSampleSize, and the overall size will become one square of the inSampleSize of the original image. Of course, there are some points to note:

  • 1. InSampleSize less than or equal to 1 will be processed according to 1
  • 2. InSampleSize can only be set to square of 2. If not square of 2, it will eventually decrease to the nearest square of 2. If setting 7 will compress it by 4, setting 15 will compress it by 8.
/**
  *
  * @param inSampleSize can calculate a reasonable inSampleSize according to your needs
  */
public static void compress(int inSampleSize) {
    File sdFile = ();
    File originFile = new File(sdFile, "");
     options = new ();
    //Set this parameter to only read the width and height of the picture into options, and will not read the entire picture into memory, preventing OOM     = true;
    Bitmap emptyBitmap = ((), options);
     = false;
     = inSampleSize;
    Bitmap resultBitmap = ((), options);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    (, 100, bos);
    try {
        FileOutputStream fos = new FileOutputStream(new File(sdFile, ""));
        (());
        ();
        ();
    } catch (FileNotFoundException e) {
        ();
    } catch (IOException e) {
        ();
    }
}

Save the image locally

 /**
      * Save bitmap to local
      * @param context the context
      * @param mBitmap the m bitmap
      * @return string
      */
    public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath;
        File filePic;
        try {
            if (().equals(Environment.MEDIA_MOUNTED)) {
                savePath = SD_PATH;
            } else {
                savePath = ().getFilesDir().getAbsolutePath() + IN_PATH;
            }
            filePic = new File(savePath + (new Date(), "yyyyMMddHHmmss") + ".jpg");
            ("LUO", "Image address====" + filePic);
            if (!()) {
                ().mkdirs();
                ();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            //No compression, save local            (, 100, fos);
            ();
            ();
        } catch (IOException e) {
            ();
            return null;
        }
        return ();
    }

The above is the detailed content of Android development to achieve image size and quality compression and saving. For more information about Android development image size and quality compression and saving, please pay attention to my other related articles!