Java image compression tool class (specify compression size)

Time:2022-5-4

Reprint:Java image compression tool class (specify compression size) – a post-90s program ape – blog Garden (cnblogs. Com)

1: Import dependency first

<!-- Thumbnail image processing -- >
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

2: Create tool class — > picutils

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @PROJECT_NAME: water_chivalry
 * @AUTHOR: Hanson-Hsc
 * @DATE: 2020-07-27 09:08
 *@ Description: picture compression tool
 * @VERSION:
 */
public class PicUtils {
  //The following are constants. According to Alibaba code development specification, magic values are not allowed in the code
    private static final Logger logger = LoggerFactory.getLogger(PicUtils.class);
    private static final Integer ZERO = 0;
    private static final Integer ONE_ZERO_TWO_FOUR = 1024;
    private static final Integer NINE_ZERO_ZERO = 900;
    private static final Integer THREE_TWO_SEVEN_FIVE = 3275;
    private static final Integer TWO_ZERO_FOUR_SEVEN = 2047;
    private static final Double ZERO_EIGHT_FIVE = 0.85;
    private static final Double ZERO_SIX = 0.6;
    private static final Double ZERO_FOUR_FOUR = 0.44;
    private static final Double ZERO_FOUR = 0.4;

    /**
     *Compress the picture according to the specified size
     *
     *@ param imagebytes source picture byte array
     *@ param desfilesize specifies the picture size in KB
     *@ return image byte array after compressed quality
     */
    public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) {
        if (imageBytes == null || imageBytes.length <= ZERO || imageBytes.length < desFileSize * ONE_ZERO_TWO_FOUR) {
            return imageBytes;
        }
        long srcSize = imageBytes.length;
        double accuracy = getAccuracy(srcSize / ONE_ZERO_TWO_FOUR);
        try {
            while (imageBytes.length > desFileSize * ONE_ZERO_TWO_FOUR) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                Thumbnails.of(inputStream)
                        .scale(accuracy)
                        .outputQuality(accuracy)
                        .toOutputStream(outputStream);
                imageBytes = outputStream.toByteArray();
            }
            logger. Info ("original image size = {} KB | compressed size = {} KB",
                    srcSize / ONE_ZERO_TWO_FOUR, imageBytes.length / ONE_ZERO_TWO_FOUR);
        } catch (Exception e) {
            logger. Error ("[picture compression] MSG = picture compression failed!", e);
        }
        return imageBytes;
    }

    /**
     *Automatic adjustment accuracy (empirical value)
     *
     *@ param size source picture size
     *@ return picture compression quality ratio
     */
    private static double getAccuracy(long size) {
        double accuracy;
        if (size < NINE_ZERO_ZERO) {
            accuracy = ZERO_EIGHT_FIVE;
        } else if (size < TWO_ZERO_FOUR_SEVEN) {
            accuracy = ZERO_SIX;
        } else if (size < THREE_TWO_SEVEN_FIVE) {
            accuracy = ZERO_FOUR_FOUR;
        } else {
            accuracy = ZERO_FOUR;
        }
        return accuracy;
    }
}

3: Compress at the interface for uploading pictures
/**
*Picture upload (special entrance for renting advertising pictures)
*/
@PostMapping(“file/img”)
@Apioperation (value = “image upload interface (ad image dedicated portal)”) public resultvo imguploads (@ requestparam (“file”) multipartfile file) throws IOException{
//Compress the picture to within the specified 120K. No matter how many megabytes your picture has, it will not exceed 120KB. The accuracy is OK and will not be blurred
byte[] bytes = PicUtils.compressPicForScale(file.getBytes(), 120);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
//Generate the image name saved in the server, and uniformly modify the original suffix to: jpg
String newFileName = UUID.randomUUID() + “.jpg”;
OSSUtil.upload2(newFileName, inputStream);
JSONObject result = new JSONObject();
result.put(“url”, OSSUtil.getUrl2(newFileName, “”));
return ResultVoUtil.success(result);
}

4. There is also a tool class for compressing pictures, but the compression size cannot be specified, but it is very useful. The compression will not lose accuracy, and the pictures are very clear:

import com.bamboo.water_chivalry.common.enums.ResultEnum;
import com.bamboo.water_chivalry.common.exception.GlobalException;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**

  • @PROJECT_NAME: water_chivalry

  • @AUTHOR: Hanson-Hsc

  • @DATE: 2020-07-20 09:24

  • @Description: picture compression tool

  • @VERSION:
    */
    public class ImgCompression {

    public static InputStream getImageCom(MultipartFile file) throws IOException {
    //Get file input stream
    InputStream inputStream = file.getInputStream();
    try {
    //Read pictures into memory
    BufferedImage bufImg = ImageIO.read(inputStream);
    //Compress the code and store the byte array of picture files
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    //This step is very important to prevent the picture from turning red
    BufferedImage bufferedImage = new BufferedImage(bufImg.getWidth(), bufImg.getHeight(), BufferedImage.TYPE_INT_RGB);
    bufferedImage.createGraphics().drawImage(bufImg,0,0, Color.WHITE,null);
    //First convert it to JPG format for compression, and then modify it to the original suffix format of the source file through OSS
    ImageIO.write(bufferedImage,”jpg”,bos);
    //Get output stream
    inputStream = new ByteArrayInputStream(bos.toByteArray());
    return inputStream;
    } catch (IOException e) {
    e.printStackTrace();
    throw new GlobalException(ResultEnum.IMG_UPLOAD_ERROR);
    }finally {
    inputStream.close();
    }
    }
    }