java 图片缩放

/**
     * @Title: ImageUtils   
     * @Description: 调整图片大小  
     * @author TimBrian
     * @since Jan 15, 20192:34:47 PM   
     * @param srcImgPath 原图片路径
     * @param targeImgPath 转换大小后图片路径
     * @param width 转换后图片宽度
     * @param height 转换后图片高度
     * @param format 转换后图片格式
     * @throws IOException
     */
    public static void resizeImage(String srcImgPath, String targeImgPath, int height, int width,String format) {
        
        File file = new File(srcImgPath);
        if (!file.exists()) {
            System.out.println("文件不存在");
            return ;
        }
        try (InputStream in = new FileInputStream(file);) {
            BufferedImage buff = ImageIO.read(file);
            int sourceHeight = buff.getHeight();
            int sourceWidth = buff.getWidth();
            //获取缩放的基数
            float percent = dealwithWH(sourceHeight,sourceWidth, height, width);
            //等比例缩放长高
            sourceHeight = (int) (sourceHeight * percent);
            sourceWidth = (int) (sourceWidth * percent);
            Image srcImg = buff;
            //生产新的图片
            buff = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_INT_RGB); 
            buff.getGraphics().drawImage(srcImg.getScaledInstance(sourceWidth, sourceHeight, Image.SCALE_SMOOTH), 0, 0, null); 
            //写出
            ImageIO.write(buff, format, new File(targeImgPath));
            
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

    private static float dealwithWH(int sourceHeight, int sourceWidth, int height, int width) {
        float percent = 0.00f;
        //如果原图片高小于原图片宽,以高为前提,算出比例
        if (sourceHeight < sourceWidth) {
            percent = (float) height / (float) sourceHeight;
            return percent;
        }else {
            percent = (float) width / (float) sourceWidth;
            return percent;
        }
    }

https://blog.csdn.net/wang20y8/article/details/86540258图片剪切

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值