Android Three Common Image Compression Methods

  • 2021-12-12 09:48:19
  • OfStack

Catalog 1, Mass Compression 2, Scale Compression (Size Compression, Sample Rate Compression) 3, Luban Compression (Recommended)

Here are three common compression methods for you

Give a set of data first

Original image: width: 2976;; height: 2976
Actual original picture:-- > byte:2299820 Mb:2.19328
Mass compression size-- > :byte:1599831 kb:1562.33496
Compress size proportionally-- > :byte:191707 kb:187.21387
Luban compression size-- > :byte:143792 kb:140.42188

Compression effect: Luban compression > Proportional compression > Mass compression

1. Mass compression


 public void getBitmap(String imgPath, String outPath) {  
        BitmapFactory.Options newOpts = new BitmapFactory.Options();  
        newOpts.inJustDecodeBounds = false;  
        newOpts.inPurgeable = true;  
        newOpts.inInputShareable = true;  
        // Do not compress  
        newOpts.inSampleSize = 1;  
        newOpts.inPreferredConfig = Config.RGB_565;  
        storeImage(bitmap, outPath); // Save Picture 
    }

Attention

Quality compression does not reduce the pixels of a picture, but changes the bit depth and transparency of a picture on the premise of keeping pixels, so as to achieve the purpose of compressing a picture, which is why this method is called quality compression method. Therefore, this method will probably not reduce the size of the picture If it is bit. compress (CompressFormat. PNG, quality, baos); This png format, quality will not work, bytes. length will not change, because png pictures are lossless and cannot be compressed

Save Picture


/**
     *  Put bitmap Convert to pictures and store them locally 
     *
     * @param bitmap
     * @param outPath  Local storage path 
     * @throws FileNotFoundException
     */
    public static boolean storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {
        FileOutputStream os = new FileOutputStream(outPath);
        boolean compressResult = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
        return compressResult;
    }

2. Proportional compression (size compression, sampling rate compression)


/**
     *  Proportional compression 
     *
     * @param path     Original picture path 
     * @param targetW  Width after compression 
     * @param targetH  Height after compression 
     * @return  Save path of compressed picture 
     */
    public static String compressScale(String path,, String outPath, int targetW, int targetH) throws FileNotFoundException {
        //  Get option  
        BitmapFactory.Options options = new BitmapFactory.Options();
        // inJustDecodeBounds Set to true, Use the option decode Come out Bitmap Yes null ,   
        //  Just store the length and width in option Medium   
        options.inJustDecodeBounds = true;
        //  At this time bitmap For null  
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        int inSampleSize = 1; // 1 Is non-scaling   
        //  Calculate the width-height scaling ratio   
        int inSampleSizeW = options.outWidth / targetW;
        int inSampleSizeH = options.outHeight / targetH;
        //  Finally, take the larger one as the scaling ratio, so as to adapt, such as wide scaling 3 Times to adapt to the screen, and   
        //  You can do it without zoom high, so if you press zoom high, the width will not be displayed in the screen   
        if (inSampleSizeW > inSampleSizeH) {
            inSampleSize = inSampleSizeW;
        } else {
            inSampleSize = inSampleSizeH;
        }
        // 1 Be sure to remember to put inJustDecodeBounds Set to false Otherwise Bitmap For null  
        options.inJustDecodeBounds = false;
        //  Set the scale ( Sampling rate )  
        options.inSampleSize = inSampleSize;
        bitmap = BitmapFactory.decodeFile(path, options);
        boolean isSuccess = storeImage(bitmap, outPath);
        if (isSuccess) {
            return outPath;
        }
        return "";
    }

This method is to set the sampling rate of the picture, reduce the picture pixel, and reduce the picture size by zooming the picture pixel.

So how do I get the size of the picture before and after compression?

Note: The size of the picture here refers to the actual size of the picture, not the size of bitmap in memory. To see the compression effect, you have to see the size of the picture in the file.


/**
     *  Get the local file size 
     *
     * @param imgPath  The path of the picture 
     * @return  The actual size of the picture, unit byte
     */
    public static int getFileSize(String imgPath) {
        int size = 0;
        try {
            FileInputStream fis = new FileInputStream(new File(imgPath));
            size = fis.available();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return size;
    }

3. Luban compression (recommended)

Luban compression is based on an algorithm, and the compression effect is basically the same as WeChat 1, almost within 200k, and the picture is not distorted.

Luban compression:
https://github.com/Curzibn/Luban

build. gradle Adding Dependencies


compile 'top.zibin:Luban:1.1.3'

private void lunBanPress(String path) {
        String pressPath = Environment.getExternalStorageDirectory().getPath();
        Luban.with(this)
                .load(path)                                   //  Pass on the list of pictures to be compressed 
                .ignoreBy(100)                                  //  Ignore the size of uncompressed pictures 
                .setTargetDir(pressPath)                        //  Set the storage location of compressed files 
                .setCompressListener(new OnCompressListener() { // Set callback 
                    @Override
                    public void onStart() {
                        // TODO  Called before compression begins, and can be started within the method  loading UI
                        Log.i(TAG, "onStart: Start Luban compression  ");
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO  Called after successful compression, returning the compressed picture file 
                        Glide.with(activity).load(file).into(iv2);
                        Log.i(TAG, "onSuccess:  Luban compression is successful   : ");
                        try {
                            int size = new FileInputStream(file).available();
                            Log.i("tag", " Luban compression  size--->:" + "byte:" + size + "    kb:"
                                    + (float) size / 1024);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO  Called when there is a problem with the compression process 
                        Log.i(TAG, "onError:  Luban compression error ");
                    }
                }).launch();    // Start compression 
    }

Source address:
https://github.com/zhouxu88/ImgCompress

It's over here ~

The above is Android 3 common picture compression details, more information about Android picture compression please pay attention to other related articles on this site!


Related articles: