java 图片视频校验,图片缩放

图片校验分辨率大小
/**
     * 获取远程图片属性
     * <p>
     *
     * @param path
     * @return
     * @throws Exception
     * @author 
     * @date 2021/12/23 15:06
     * @version 1.0.0
     */
    public static FilePictureAttributeDTO pictureAttribute(String path) {
        FilePictureAttributeDTO res = null;
        FileInputStream inputStream = null;
        try {
            long l = System.currentTimeMillis();
            if (StringUtils.isBlank(path)) {
                return res;
            }
            File file = new File(path);
            long l1 = System.currentTimeMillis();
            inputStream = new FileInputStream(file);
            BufferedImage bi = ImageIO.read(inputStream);
            log.info("pictureAttribute_url-ImageIO.read耗时:{}", System.currentTimeMillis() - l1);

            res = new FilePictureAttributeDTO().setWidth(bi.getWidth()).setHeight(bi.getHeight()).setSize(file.length());

            log.info("pictureAttribute_url-返回:{},总耗时:{}", JSON.toJSONString(res), System.currentTimeMillis() - l);
        } catch (Exception ex) {
            log.error("{} - pictureAttribute_url-获取图片像素异常:{}", path, ex);
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return res;
    }


    /**
     * 获取远程图片属性
     * <p>
     *
     * @param url
     * @return
     * @throws Exception
     * @author 
     * @date 2021/12/23 15:06
     * @version 1.0.0
     */
    public static FilePictureAttributeDTO pictureAttribute_url(String url) {
        FilePictureAttributeDTO res = null;
        File tempFile = null;
        FileOutputStream fileOutputStream = null;
        try {
            if (StringUtils.isBlank(url)) {
                return res;
            }
            long l = System.currentTimeMillis();
            URL remoteUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) remoteUrl.openConnection();
            connection.setRequestMethod("GET");
            InputStream inputStream = connection.getInputStream();

            tempFile = File.createTempFile(UUID.randomUUID().toString().replaceAll("-", ""), url.substring(url.lastIndexOf(".")));
            fileOutputStream = new FileOutputStream(tempFile);
            IoUtil.copy(inputStream, fileOutputStream);
            log.info("pictureAttribute_url-下载到本地远程图片耗时:{}", System.currentTimeMillis() - l);

            long l1 = System.currentTimeMillis();
            BufferedImage bi = ImageIO.read(tempFile);
            log.info("pictureAttribute_url-ImageIO.read耗时:{}", System.currentTimeMillis() - l1);

            res = new FilePictureAttributeDTO().setWidth(bi.getWidth()).setHeight(bi.getHeight()).setSize(tempFile.length());

            log.info("pictureAttribute_url-返回:{},总耗时:{}", JSON.toJSONString(res), System.currentTimeMillis() - l);
        } catch (Exception ex) {
            log.error("{} - pictureAttribute_url-获取图片像素异常:{}", url, ex);
        } finally {
            if (null != fileOutputStream) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != tempFile) {
                tempFile.delete();
            }
        }
        return res;
    }
@Data
@Accessors(chain = true)
public class FilePictureAttributeDTO {

    /**
     * 宽
     */
    private Integer width;

    /**
     * 高
     */
    private Integer height;

    /**
     * 大小
     */
    private Long size;

    /**
     * 格式
     */
    private String format;

}
视频分辨率帧数大小校验
/**
     * 视频属性获取
     * <p>
     *
     * @param path 本地视频地址
     * @return
     * @author 
     * @date 2021/12/23 14:31
     * @version 1.0.0
     */
    public static FileVideoAttributeDTO videoAttribute(String path) {
        FileVideoAttributeDTO res = null;
        if (StringUtils.isBlank(path)) {
            return res;
        }
        FileChannel fc = null;
        try {
            long l = System.currentTimeMillis();
            File source = new File(path);
            Encoder encoder = new Encoder();

            it.sauronsoftware.jave.MultimediaInfo m = encoder.getInfo(source);

            FileInputStream fis = new FileInputStream(source);
            fc = fis.getChannel();

            if (null == m.getVideo()) {
                throw new BusinessException(500, "解析视频video为空");
            }
            res = new FileVideoAttributeDTO().setVideoTime(m.getDuration() / 1000)
                    .setHeight(m.getVideo().getSize().getHeight())
                    .setWidth(m.getVideo().getSize().getWidth())
                    .setFrameRate(m.getVideo().getFrameRate())
                    .setBitRate(m.getVideo().getBitRate())
                    .setFormat(m.getFormat())
                    .setSize(fc.size())
            ;

            log.info("videoAttribute获取视频属性返回:{},耗时:{}", JSON.toJSONString(res), System.currentTimeMillis() - l);
            return res;

//            BigDecimal fileSize = new BigDecimal(fc.size());
//            size = fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP) + "MB";
        } catch (Exception e) {
            log.error("{} - videoAttribute获取视频属性异常:{}", path, e);
        } finally {
            if (null != fc) {
                try {
                    fc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return res;
    }

    /**
     * 视频属性获取
     * <p>
     *
     * @param url 远程视频地址
     * @return
     * @author 
     * @date 2021/12/23 14:31
     * @version 1.0.0
     */
    public static FileVideoAttributeDTO videoAttribute_url(String url) {
        FileVideoAttributeDTO res = null;
        if (StringUtils.isBlank(url)) {
            return res;
        }
        FileChannel fc = null;
        FileOutputStream fileOutputStream = null;
        File tempFile = null;
        InputStream inputStream = null;
        try {
            long l = System.currentTimeMillis();
            URL remoteUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) remoteUrl.openConnection();
            connection.setRequestMethod("GET");
            inputStream = connection.getInputStream();

            tempFile = File.createTempFile(UUID.randomUUID().toString().replaceAll("-", ""), url.substring(url.lastIndexOf(".")));
            fileOutputStream = new FileOutputStream(tempFile);
            IoUtil.copy(inputStream, fileOutputStream);
            log.info("videoAttribute_url-下载远程视频至本地耗时:{}", (System.currentTimeMillis() - l));

            long l3 = System.currentTimeMillis();
            Encoder encoder = new Encoder();

            it.sauronsoftware.jave.MultimediaInfo m = encoder.getInfo(tempFile);
            log.info("encoder.getInfo解析视频耗时:{}", (System.currentTimeMillis() - l3));

            FileInputStream fis = new FileInputStream(tempFile);
            fc = fis.getChannel();

            if (null == m.getVideo()) {
                throw new BusinessException(500, "解析视频video为空");
            }
            res = new FileVideoAttributeDTO().setVideoTime(m.getDuration() / 1000)
                    .setHeight(m.getVideo().getSize().getHeight())
                    .setWidth(m.getVideo().getSize().getWidth())
                    .setFormat(m.getFormat())
                    .setFrameRate(m.getVideo().getFrameRate())
                    .setBitRate(m.getVideo().getBitRate())
                    .setSize(fc.size())
            ;

            log.info("videoAttribute获取视频属性返回:{},耗时:{}", JSON.toJSONString(res), System.currentTimeMillis() - l);
            return res;

//            BigDecimal fileSize = new BigDecimal(fc.size());
//            size = fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP) + "MB";
        } catch (Exception e) {
            log.error("{} - videoAttribute获取视频属性异常:{}", url, e);
        } finally {
            if (null != fc) {
                try {
                    fc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != fileOutputStream) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != tempFile) {
                tempFile.delete();
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return res;
    }
@Data
@Accessors(chain = true)
public class FileVideoAttributeDTO {

    /**
     * 时长(s)
     */
    private Long videoTime;

    /**
     * 宽
     */
    private Integer width;

    /**
     * 高
     */
    private Integer height;

    /**
     * 大小
     */
    private Long size;

    /**
     * 格式
     */
    private String format;

    /**
     * 帧数
     */
    private Float frameRate;

    /**
     * 比特率
     */
    private Integer bitRate;
}
        <dependency>
            <groupId>com.github.vip-zpf</groupId>
            <artifactId>jave</artifactId>
            <version>1.0.9</version>
        </dependency>
       
图片缩放
 public static void main(String[] args) {
        thumbnail("D:\\70380f81-4752-4cde-bb0f-51101df6bbc8.jpg");
        thumbnail("D:\\3131321.png");
        thumbnail("D:\\eee.jpg");
        thumbnail("D:\\long.jpg");
        thumbnail("D:\\zyun.jpg");
        thumbnail("D:\\微信图片_20211228110440.jpg");
    }

    /**
     * 等比例压缩
     * <p>
     *
     * @param path
     * @return
     * @author 
     * @date 2021/12/24 17:48
     * @version 1.0.0
     */
    public static String thumbnail(String path) {
        OutputStream os = null;
        String newPath = null;
        try {
            newPath = "D:\\thumb\\" + UUID.randomUUID().toString().replace("-", "") + path.substring(path.lastIndexOf("."));
            File file = new File(newPath);
            os = new FileOutputStream(file);

            Image image = ImageIO.read(new FileInputStream(path));
            int width = image.getWidth(null);// 获得原图的宽度
            int height = image.getHeight(null);// 获得原图的高度

            System.err.println("原来width:" + width + ",height:" + height);

            BigDecimal rate = bl(Long.valueOf(height), Long.valueOf(width), 1080L, 1440L);

            // 计算缩略图最总的宽度和高度
            int newWidth = BigDecimal.valueOf(width).multiply(rate).intValue();// 宽度缩略比例
            int newHeight = BigDecimal.valueOf(height).multiply(rate).intValue();// 高度缩略比例

            BufferedImage bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            bufferedImage.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, image.SCALE_SMOOTH), 0, 0, null);

            ImageIO.write(bufferedImage, path.substring(path.lastIndexOf(".") + 1), os);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return newPath;
    }

 /**
     * 获取缩放比例
     * <p>
     *
     * @param height 图片高
     * @param weight 图片宽
     * @param bzH    图片标准高
     * @param bzW    图片标准宽
     * @return
     * @author 
     * @date 2021/12/28 10:55
     * @version 1.0.0
     */
    public static BigDecimal bl(Long height, Long weight, Long bzH, Long bzW) {
        if (null == height || null == weight || null == bzH || null == bzW) {
            return BigDecimal.ONE;
        }
        BigDecimal b1 = (BigDecimal.valueOf(bzH).divide(BigDecimal.valueOf(height), 5, RoundingMode.HALF_UP)).compareTo(BigDecimal.ONE) > 0 ? BigDecimal.ONE :
                (BigDecimal.valueOf(bzH).divide(BigDecimal.valueOf(height), 5, RoundingMode.HALF_UP));
        BigDecimal b2 = (BigDecimal.valueOf(bzW).divide(BigDecimal.valueOf(weight), 5, RoundingMode.HALF_UP)).compareTo(BigDecimal.ONE) > 0 ? BigDecimal.ONE :
                (BigDecimal.valueOf(bzW).divide(BigDecimal.valueOf(weight), 5, RoundingMode.HALF_UP));


        BigDecimal rate = BigDecimal.ONE;
        if (b1.compareTo(BigDecimal.ONE) >= 0 && b2.compareTo(BigDecimal.ONE) < 0) {
            rate = b2;
        } else if (b2.compareTo(BigDecimal.ONE) >= 0 && b1.compareTo(BigDecimal.ONE) < 0) {
            rate = b1;
        } else if (b1.compareTo(BigDecimal.ONE) < 0 && b2.compareTo(BigDecimal.ONE) < 0) {
            rate = b1.compareTo(b2) > 0 ? b1 : b2;
        }

        return rate;
    }
 		<dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值