java在上传视频时生成预览图

视频封面图生成

在圣品上传时往往需要生成一张预览图(缩略图),如果在非特殊情况下让用户单独上传,会造成工作压力,此时可以用视频中某一帧作为封面图,实现方式如下:

public class ImageUtil {

    /**
     * 生成截图
     * @param filePath 视频文件本地路径
     * @param targerFilePath 目标文件夹
     * @param targetFileName 目标文件名
     * @return 图片文件路径
     * @throws Exception
     */
    public static String randomGrabberFFmpegImage(String filePath, String targerFilePath, String targetFileName)
            throws Exception {
        System.out.println(filePath);
        FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(filePath);
        ff.start();
        Frame f;
        int lenght = ff.getLengthInFrames();
        int i = 0;
        String path = null;
        while (i < lenght) {
            // 过滤前5帧,避免出现全黑的图片,依自己情况而定
            f = ff.grabFrame();
            if ((i > 200) && (f.image != null)) {
                path = doExecuteFrame(f, targerFilePath, targetFileName);
                break;
            }
            i++;
        }

        ff.stop();
        return path;
    }

    public static String doExecuteFrame(Frame f, String targerFilePath, String targetFileName) {

        if (null ==f ||null ==f.image) {
            throw new GlobleException("获取缩略图失败");
        }
        Java2DFrameConverter converter =new Java2DFrameConverter();
        String imageMat ="jpg";
        String FileName =targerFilePath + File.separator +targetFileName +"." +imageMat;
        BufferedImage bi =converter.getBufferedImage(f);
        System.out.println("width:" + bi.getWidth());
        System.out.println("height:" + bi.getHeight());
        File output =new File(FileName);
        try {
            ImageIO.write(bi,imageMat,output);
        }catch (IOException e) {
            throw new GlobleException("缩略图写入文件夹失败");
        }
        return FileName;
    }

    public static void main(String[] args) throws Exception {
        String s = randomGrabberFFmpegImage("/home/xiao/IMG_3077.mp4", "/home/xiao", "213");
        System.out.println(s);
    }
}

 

转载于:https://my.oschina.net/u/3042999/blog/1830800

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值