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

发布时间:2023年12月17日

工具类

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;
    }
}

文章来源:https://blog.csdn.net/MS_SONG/article/details/135010945
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。