压缩图片大小

腾讯图片文字识别有大小限制, 最大5M, 所以对于大图片需要进行缩小处理

一. 参考链接

图片压缩算法java实现 java压缩图片至指定大小

二. java代码

package com.example.springboot2.picture;

import org.junit.jupiter.api.Test;

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


/**
 * 图片处理类
 *
 * @author yyq
 */
public class ImageUtil {


    /**
     * 生成缩略图
     *
     * @param oidPath 文件大小
     * @param newPath 原文件路径
     * @param smallSize 文件压缩倍数
     * @return
     */
    public static boolean imageGenerateSmall(String oidPath, String newPath, double smallSize) {
        try {
            File bigFile = new File(oidPath);
            Image image = ImageIO.read(bigFile);
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            int widthSmall = (int) (width / smallSize);
            int heightSmall = (int) (height / smallSize);
            BufferedImage buffi = new BufferedImage(widthSmall, heightSmall, BufferedImage.TYPE_INT_RGB);
            Graphics g = buffi.getGraphics();
            g.drawImage(image, 0, 0, widthSmall, heightSmall, null);
            g.dispose();
            ImageIO.write(buffi, "jpg", new File(newPath));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 图片压缩,图片大小超过100K自动按比例压缩到100K以下
     *
     * @param fileSize 文件大小
     * @param oidPath 原文件路径
     * @param newPath 压缩后路径
     * @return
     * @throws Exception
     */
    public static boolean imageCompress(long fileSize, String oidPath, String newPath) throws Exception {
        boolean rs = true;
        int kb = 3000 * 1024;
        if (fileSize > 100 * 1024) {
            int smallSize = (int) (fileSize % kb == 0 ? fileSize / kb : fileSize / kb + 1);
            double size = Math.ceil(Math.sqrt(smallSize));
            rs = ImageUtil.imageGenerateSmall(oidPath, newPath, size);
        }
        return rs;
    }


    @Test
    public void main22() throws Exception {

        File fileList = new File("E:\\documents\\DCIM\\unfinished\\盐城市歌谣谚语卷彩色");
        String savePath = "E:\\documents\\DCIM\\unfinished\\test223\\";
        for (File file : fileList.listFiles()) {

            imageCompress(file.length(), file.getAbsolutePath(), savePath + file.getName());

        }

    }



}



三.效果

可以将6M的图片压缩到600kb, 清晰度变化不大

你可能感兴趣的:(开发语言,java)