简体   繁体   中英

How to reduce PNG/JPEG file size in spring boot

I want to reduce the file size while saving the image. Please, take this code for reference. And how to reduce the file size.

public void saveImage(MultipartFile image_one, MultipartFile image_two, MultipartFile image_three) throws Exception{
        System.out.println("Inside Save image Repo");
        
        String folder = "C:/Users/HP/Photos";
        byte[] bytes_one;
        try {
            bytes_one = image_one.getBytes();
            
            Path path1 = Paths.get(folder + image_one.getOriginalFilename()); 
            System.out.println("Path of 1st imagae : "+path1);
            
            Files.write(path1, bytes_one);
            
            System.out.println("Image-1 size : "+bytes_one.length);
        } catch (Exception e) {
            System.out.println("Inside Catch Block -> Image not found ");
            e.printStackTrace();
        }   
    }

You could use the Java javax.imageio library and use a function to compress your image bytes.

This should do the work:

public byte[] compressImage(MultipartFile image) throws IOException
{

    InputStream inputStream = image.getInputStream();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    float imageQuality = 0.3f;

    // Create the buffered image
    BufferedImage bufferedImage = ImageIO.read(inputStream);

    // Get image writers
    Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("jpg"); // Input your Format Name here

    if (!imageWriters.hasNext())
        throw new IllegalStateException("Writers Not Found!!");

    ImageWriter imageWriter = imageWriters.next();
    ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
    imageWriter.setOutput(imageOutputStream);

    ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();

    // Set the compress quality metrics
    imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    imageWriteParam.setCompressionQuality(imageQuality);

    // Compress and insert the image into the byte array.
    imageWriter.write(null, new IIOImage(bufferedImage, null, null), imageWriteParam);

    byte[] imageBytes = outputStream.toByteArray();

    // close all streams
    inputStream.close();
    outputStream.close();
    imageOutputStream.close();
    imageWriter.dispose();


    return imageBytes;
}

It returns the compressed image bytes so that the value returned can be transformed into a number of things. In your case, in a file...

byte[] compressedImageBytes = compressImage(imageOne);

Files.write(path1, bytesOne);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM