Java 实现图片压缩、裁剪

Java 实现图片压缩、裁剪

1、引入依赖

<!--hutool 工具-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.11</version>
</dependency>

2、文件加工

注意:大部分的IO流是无法重复读取的,只能读取一次,再读取时,会抛出异常,我们这里使用ByteArrayOutputStream将流数据缓存到内存中,达到多次读取的目的

import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;

public class ImageUtil {

    /**
     * 图片加工方法
     * <p>
     * 支持的图片格式: BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif
     *
     * @param imgUrl       目标文件的地址
     * @param outputStream 输出流
     * @param width        图片裁剪后的宽度
     * @param height       图片裁剪后的高度
     * @throws IOException
     */
    public static void imageProcess(String imgUrl, ByteArrayOutputStream outputStream, 
                                    int width, int height) throws IOException {
        byte[] imgBytes = getImgBytes(imgUrl);
        try (InputStream pojoInputStream = new ByteArrayInputStream(imgBytes);
             InputStream readInputStream = new ByteArrayInputStream(imgBytes)) {
            // 图片对象
            BufferedImage bufferedImage = ImageIO.read(pojoInputStream);
            // 高度
            float imgHeight = Float.parseFloat(String.valueOf(bufferedImage.getHeight()));
            // 缩放比例
            float scale = 1 / (imgHeight / height);
            // 矩形对象
            Rectangle rectangle = new Rectangle(0, 0, width, height);

            Img.from(readInputStream)    // 读文件
                    .scale(scale)        // 压缩
                    .cut(rectangle)      // 裁剪
                    .write(outputStream);// 写文件
        }
    }

    /**
     * 获取文件二进制数据
     *
     * @param imgUrl 图片地址
     * @return 二进制数据
     * @throws IOException
     */
    public static byte[] getImgBytes(String imgUrl) throws IOException {
        try (InputStream inputStream = getImgInputStream(imgUrl);
             ByteArrayOutputStream swapStream = new ByteArrayOutputStream()) {
            int rc;
            byte[] buff = new byte[100];
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            return swapStream.toByteArray();
        }
    }

    /**
     * 获取文件输入流
     *
     * @param imgUrl 图片地址
     * @return 输入流
     * @throws IOException
     */
    public static InputStream getImgInputStream(String imgUrl) throws IOException {
        InputStream inputStream;
        try {
            // 网络图片
            URL url = new URL(imgUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            inputStream = connection.getInputStream();
        } catch (Exception urlException) {
            // 本地图片
            File file = FileUtil.file(imgUrl);
            inputStream = Files.newInputStream(file.toPath());
        }
        return inputStream;
    }
}


Img 方法详情 参考官网:官网

3、测试

public static void main(String[] args) {
    try (ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
         OutputStream outputStream = Files.newOutputStream(new File("D:/testImg.jpg").toPath())) {
        String url = "https://cn.bing.com/th?id=OHR.SunriseCastle_ZH-CN6235928386_1920x1080.jpg";
        ImageUtil.imageProcess(url, arrayOutputStream, 600, 1024);
        arrayOutputStream.writeTo(outputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值