压缩图片-工作常用小工具02

这段代码主要实现了读取指定目录下图片,进行旋转和压缩处理。如果图片大于1MB,会使用imgscalr库将其压缩到1MB以下,并保存到目标路径。涉及到的技术包括Java的ImageIO、MetadataReader用于读取图片元数据,以及Scalr库进行图片尺寸调整和压缩。
摘要由CSDN通过智能技术生成

压缩旋转图片

需要引入两个包imgscalr , metadata请自行下载

 public static void main(String[] args) throws IOException {
        //准备压缩图片路径
        String path = “”
        //压缩成功放置路径
        String path01 = “”;
        File file = new File(path);
        File filelist[] = file.listFiles();
        Boolean flag01 = false;
        for (File f : filelist) {
            String filename = f.getName();
            //System.out.println("获取到的文件名"+filename);
            //String[] spart = filename.split("-");
            //旋转图片
            ImageUtil.change(f);
            System.out.println("图片小于1mb不需要压缩"+(f.length() > 1000 * 1024));
            //判断图片大小
            if (filename.endsWith("jpg")&f.length() > 1000 * 1024) {
                File zipFile = new File(path01+filename);
                System.out.println("开始压缩文件: " + f.getAbsolutePath());
                //ImageUtil.change(f);
                //开始压缩
                ImageUtil.compressUnderSize(f,1000 * 1024,zipFile);
            }
        }
    }

以下为工具方法

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifIFD0Directory;
import org.imgscalr.Scalr;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;

public class ImageUtil {

	/**
     * 将图片压缩到指定大小以内
     *
     * @param //srcImgData 源图片数据
     * @param maxSize 目的图片大小
     * @return
     * @author CY
     * @date 2020年11月18日
     */
    public static void compressUnderSize(File imageFile, long maxSize, File zipFile) throws IOException {
        byte[] data = getByteByPic(imageFile);
        byte[] imgData = Arrays.copyOf(data, data.length);
        do {
            try {
                imgData = compress(imgData, 0.9);
            } catch (IOException e) {
                throw new IllegalStateException("压缩图片过程中出错,请及时联系管理员!", e);
            }
        } while (imgData.length > maxSize);
        System.out.println("压缩后图片大小为"+imgData.length);
        byteToImage(imgData, zipFile);
    }

    /**
     * 获取图片文件字节
     *
     * @param imageFile
     * @return
     * @throws IOException
     * @author CY
     * @date 2020年11月18日
     */
    public static byte[] getByteByPic(File imageFile) throws IOException {
        InputStream inStream = new FileInputStream(imageFile);
        BufferedInputStream bis = new BufferedInputStream(inStream);
        BufferedImage bm = ImageIO.read(bis);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        String imageUrl = imageFile.getAbsolutePath();
        String type = imageUrl.substring(imageUrl.length() - 3);
        ImageIO.write(bm, type, bos);
        bos.flush();
        byte[] data = bos.toByteArray();
        return data;
    }

    /**
     * 按照宽高比例压缩
     *
     * @param srcImgData 待压缩图片输入流
     * @param scale 压缩刻度
     * @return
     * @throws IOException
     * @author CY
     * @date 2020年11月18日
     */
    public static byte[] compress(byte[] srcImgData, double scale) throws IOException {
        BufferedImage bi = ImageIO.read(new ByteArrayInputStream(srcImgData));
        int width = (int) (bi.getWidth() * scale); // 源图宽度
        int height = (int) (bi.getHeight() * scale); // 源图高度
        Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.setColor(Color.RED);
        g.drawImage(image, 0, 0, null); // 绘制处理后的图
        g.dispose();
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ImageIO.write(tag, "JPEG", bOut);
        return bOut.toByteArray();
    }

    public static void change(File inBuffer) throws IOException {
        BufferedInputStream file11 = new BufferedInputStream(new FileInputStream(inBuffer));
        Metadata metaData = null;
        boolean isExif = true;
        try {
            metaData = ImageMetadataReader.readMetadata(file11, false);
        } catch (IOException io) {
            throw io;
        } catch (Throwable e) {
            isExif = false;
        }

        int orientation = 0;
        if (isExif) {
            if (metaData != null) {
                Directory directory = metaData
                        .getDirectory(ExifIFD0Directory.class);
                try {
                    if (directory != null) {
                        orientation = directory
                                .getInt(ExifIFD0Directory.TAG_ORIENTATION);
                    } else {
                        orientation = 1;
                    }
                } catch (MetadataException e) {
                    orientation = 1;
                }
            } else {
                orientation = 1;
            }
        }
        BufferedImage orgImageSrc = ImageIO.read(inBuffer);
        //File zipFile = new File("C:\\Users\\18404\\Desktop\\2.jpg");
        BufferedImage orgImage ;
        switch (orientation) {
            case 0:
                //付振伟
                orgImage = Scalr.rotate(orgImageSrc, Scalr.Rotation.FLIP_HORZ,
                        Scalr.OP_ANTIALIAS);
                //ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                ImageIO.write(orgImage,"jpg",inBuffer);
                System.out.println("旋转成功0"+inBuffer);
                break;
            case 1:
                orgImage = orgImageSrc;
                //ImageIO.write(orgImage,"jpg",inBuffer);
                System.out.println("无需旋转");
                break;
            case 3:
                orgImage = Scalr.rotate(orgImageSrc, Scalr.Rotation.CW_180,
                        Scalr.OP_ANTIALIAS);
                ImageIO.write(orgImage,"jpg",inBuffer);
                break;
            case 6:
                orgImage = Scalr.rotate(orgImageSrc, Scalr.Rotation.CW_90,
                        Scalr.OP_ANTIALIAS);
                //ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                ImageIO.write(orgImage,"jpg",inBuffer);
                System.out.println("旋转成功6"+inBuffer);
                break;
            case 8:
                orgImage = Scalr.rotate(orgImageSrc, Scalr.Rotation.CW_270,
                        Scalr.OP_ANTIALIAS);
                ImageIO.write(orgImage,"jpg",inBuffer);
                break;
            default:
                orgImage = orgImageSrc;
                ImageIO.write(orgImage,"jpg",inBuffer);
                break;
        }
    }

    /**
     * byte数组转图片
     *
     * @param data
     * @param //path
     * @author CY
     * @date 2020年11月18日
     */
    public static void byteToImage(byte[] data, File zipFile) {
        if (data.length < 3)
            return;
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(zipFile);
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值