生成缩略图~java

话不多说直接上代码:

public class ImageUtil {

    /**
     * 生成缩略图
     * @param input  资源文件
     * @param outputPath    生成缩略图文件夹路径
     * @param shrink    缩放比例
     * @throws IOException
     */
    public static File shrinkPic(File input, String outputPath, double shrink) throws IOException {

        String name = input.getName();
        // 读取原始图像文件
        // 创建BufferedImage对象来存储原始图像数据
        BufferedImage originalImage = ImageIO.read(input);
        // 设置新的图像大小(这里将图像缩小为原来的1/2)
        int scaledWidth = (int) (originalImage.getWidth() * shrink);
        int scaledHeight = (int) (originalImage.getHeight() * shrink);

        // 创建目标图像对象并指定新的大小
        BufferedImage resizedImage = new BufferedImage(scaledWidth, scaledHeight, originalImage.getType());
        // 获得Graphics2D对象以进行操作
        Graphics graphics = resizedImage.getGraphics();
        // 调用drawImage()方法进行缩放处理
        graphics.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
        // 释放Graphics2D对象
        graphics.dispose();
        // 输出结果到文件或显示在界面上等等...
        File output = new File(outputPath + File.separator + name);
        ImageIO.write(resizedImage, "jpg", output);

        return output;
    }



    /**
     * 生成缩略图
     * @param input  资源文件输入流
     * @param outputPath    生成缩略图文件夹路径
     * @param shrink    缩放比例
     * @throws IOException
     */
    public static File shrinkPic(InputStream input, String outputPath, double shrink) throws IOException {

        // 读取原始图像文件
        // 创建BufferedImage对象来存储原始图像数据
        BufferedImage originalImage = ImageIO.read(input);
        // 设置新的图像大小(这里将图像缩小为原来的1/2)
        int scaledWidth = (int) (originalImage.getWidth() * shrink);
        int scaledHeight = (int) (originalImage.getHeight() * shrink);

        // 创建目标图像对象并指定新的大小
        BufferedImage resizedImage = new BufferedImage(scaledWidth, scaledHeight, originalImage.getType());
        // 获得Graphics2D对象以进行操作
        Graphics graphics = resizedImage.getGraphics();
        // 调用drawImage()方法进行缩放处理
        graphics.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
        // 释放Graphics2D对象
        graphics.dispose();
        // 输出结果到文件或显示在界面上等等...
        File output = new File(outputPath);
        if (!output.getParentFile().getParentFile().exists()) {
            output.getParentFile().mkdirs();
        }
        if (!output.getParentFile().exists()) {
            output.mkdirs();
        }
        ImageIO.write(resizedImage, "jpg", output);

        return output;
    }


}

上面两个方法都是返回缩略后的图片文件,不同的是一个传的文件File,一个传的是文件流。

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值