Home  >  Article  >  Java  >  How to compress image size in Java

How to compress image size in Java

WBOY
WBOYforward
2023-04-19 16:28:122189browse

Usage scenarios:

1. When using the image upload function, the uploaded image is too large, causing too much use of server resources.
2. The size of the image uploaded by the client is different, and the front-end needs When displaying a fixed size to the user, the uploaded images can be processed uniformly through java

Function preview

1. Before compression

How to compress image size in Java

2. After compression

How to compress image size in Java

code implementation:

package com.linghu.test;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * @author 在下令狐
 * @describe  压缩图片大小
 * @date 2020/6/12
 */
public class TestCompressImage {
    public static void main(String[] args) {
        try {
            //图片所在路径
            BufferedImage templateImage = ImageIO.read(new File("f:/temp/linghu.jpg"));


            //原始图片的长度和宽度
            int height = templateImage.getHeight();
            int width = templateImage.getWidth();

            //通过比例压缩
            float scale = 0.5f;

            //通过固定长度压缩
            /*int doWithHeight = 100;
            int dowithWidth = 300;*/

            //压缩之后的长度和宽度
            int doWithHeight = (int) (scale * height);
            int dowithWidth = (int) (scale * width);

            BufferedImage finalImage = new BufferedImage(dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB);

            finalImage.getGraphics().drawImage(templateImage.getScaledInstance(dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);


            //图片输出路径,以及图片名
            FileOutputStream  fileOutputStream = new FileOutputStream("f:/temp/linghuAfterDoWith.jpg");
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
            encoder.encode(finalImage);
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The above is the detailed content of How to compress image size in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete