【实用】Java实现调节图片大小、压缩占用空间

工具类

package com.song.springclouddemoshardingjdbc.utils;


import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

public class ImageUtils {
    /**
     * 通过BufferedImage图片流调整图片大小
     */
    public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
        Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_AREA_AVERAGING);
        BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        outputImage.getGraphics().drawImage(resultingImage, 0, 0, null);
        return outputImage;
    }


    /**
     * BufferedImage图片流转byte[]数组
     */
    public static byte[] imageToBytes(BufferedImage bImage) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, "jpg", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }


    /**
     * byte[]数组转BufferedImage图片流
     */
    private static BufferedImage bytesToBufferedImage(byte[] ImageByte) {
        ByteArrayInputStream in = new ByteArrayInputStream(ImageByte);
        BufferedImage image = null;
        try {
            image = ImageIO.read(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }



    /**
     * 通过指定压缩质量压缩图片,并保存到目标文件
     */
    public static void compressImageWithQuality(BufferedImage image, File outputFile, double compressionQuality) throws IOException {
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer = writers.next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile);
        writer.setOutput(ios);

        // 设置压缩质量参数
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality((float) compressionQuality);

        // 写入文件
        writer.write(null, new IIOImage(image, null, null), param);

        // 关闭资源
        ios.flush();
        ios.close();
        writer.dispose();
    }
}



实现

package com.song.springclouddemoshardingjdbc.controller;
//
//
//import com.song.springclouddemoshardingjdbc.utils.ImageUtils;
//
//import javax.imageio.ImageIO;
//import java.awt.image.BufferedImage;
//import java.io.IOException;
//import java.io.File;
//import java.net.URL;
//
//
//public class TestController {
//
//    public static void main(String[] args) {
//        try {
//            //通过url获取BufferedImage图像缓冲区
//            //URL img = new URL("https://s2.loli.net/2023/12/14/ShOoytfRnrCakse.jpg");
//            URL img = new URL("https://gitee.com/song-rice/upload-image/raw/2bb7a342209089bf38fc971851f25d5ba77e7ce6/%E7%99%BD%E5%BA%95%E8%AF%81%E4%BB%B6%E7%85%A7_215x300.jpg");  //证件照
//            BufferedImage image = ImageIO.read(img);
//            //获取图片的宽、高
//            System.out.println("Width: " + image.getWidth());
//            System.out.println("Height: " + image.getHeight());
//            //调整图片大小为 400X400尺寸
//            BufferedImage newImage = ImageUtils.resizeImage(image, 215, 300);
//            //将缓冲区图片保存到 F:/test/pic1.jpg (文件不存在会自动创建文件保存,文件存在会覆盖原文件保存)
//            ImageIO.write(newImage, "jpg", new File("F:/pic3.jpg"));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//}


import com.song.springclouddemoshardingjdbc.utils.ImageUtils;

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

import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class TestController {


    public static void main(String[] args) {
        try {
            // 通过URL获取BufferedImage图像缓冲区
            URL img = new URL("https://gitee.com/song-rice/upload-image/raw/2bb7a342209089bf38fc971851f25d5ba77e7ce6/%E7%99%BD%E5%BA%95%E8%AF%81%E4%BB%B6%E7%85%A7_215x300.jpg");  //证件照
            BufferedImage image = ImageIO.read(img);

            // 调整图片大小为 215x300尺寸
            BufferedImage resizedImage = ImageUtils.resizeImage(image, 215, 300);

            // 压缩图片到目标文件大小
            File compressedFile = compressImage(resizedImage, 30);

            // 输出压缩后图片的文件大小
            long fileSizeInBytes = compressedFile.length();
            System.out.println("Compressed Image File Size: " + fileSizeInBytes + " bytes");

            // 将修改后的文件输出到当前用户桌面 
            File desktop = new File(System.getProperty("user.home"), "Desktop");
            File output = new File(desktop, "compressed.jpg");
            Files.copy(compressedFile.toPath(), output.toPath(), StandardCopyOption.REPLACE_EXISTING);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /*
        压缩图片
     */
    private static File compressImage(BufferedImage image, int targetFileSizeKb) throws IOException {
        double targetFileSizeBytes = targetFileSizeKb * 1024;  // 目标文件大小(字节)

        double compressionQuality = 1.0;  // 初始压缩质量
        double maxCompressionQuality = 0.1;  // 最大压缩质量

        File compressedFile = null;
        while (compressionQuality > maxCompressionQuality) {
            // 创建临时文件
            compressedFile = File.createTempFile("compressed", ".jpg");
            // 将图像保存到临时文件中
            ImageIO.write(image, "jpg", compressedFile);

            // 计算当前压缩后的文件大小
            long fileSizeInBytes = compressedFile.length();

            // 如果当前文件大小小于等于目标大小,则结束压缩循环
            if (fileSizeInBytes <= targetFileSizeBytes) {
                break;
            }

            // 调整压缩质量
            compressionQuality -= 0.1;
            ImageUtils.compressImageWithQuality(image, compressedFile, compressionQuality);
        }

        return compressedFile;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宋大米Pro

感谢小主大赏,留言可进互助群~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值