package cn.wisenergy.common.utils;


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;


/**
 * 截取视频图片
 *
 * @ClassName: FrameGrabberKit
 */
public class FrameGrabberKit {

    /**
     * 获取视频图片
     *
     * @param videofile 源视频文件路径
     * @param framefile 截取帧的图片存放路径
     * @param imgfile   视频封面图保存路径
     * @return
     */
    public static String getVedioImg(String videofile, String framefile, String imgfile) {
        String ImgUrl = "";
        //截取封面图
        try {
            fetchFrame(videofile, framefile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 完整的ImgUrl
        ImgUrl = imgfile;//视频封面图保存路径
        return ImgUrl;
    }

    /**
     * 获取指定视频的帧并保存为图片至指定目录
     *
     * @param videofile 源视频文件路径
     * @param framefile 截取帧的图片存放路径 例：F:\hfkjrecorder\target\4.jpg
     * @throws Exception
     */
    public static void fetchFrame(String videofile, String framefile) throws Exception {
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile);
        ff.start();
        int lenght = ff.getLengthInFrames();
        int i = 0;
        int interceptionFrames = 30;//截取第几帧
        //默认截取第50帧，如果第50帧大于视频总帧数的8成直接取长度lenght * 0.3
        if (interceptionFrames >= lenght * 0.8) {
            interceptionFrames = (int) (lenght * 0.3);
        }
        Frame f = null;
        while (i < lenght) {
            // 过滤 前  interceptionFrames 帧，避免出现全黑的图片，依自己情况而定
            f = ff.grabFrame();
            if ((i > interceptionFrames) && (f.image != null)) {
                break;
            }
            i++;
        }

        int owidth = f.imageWidth;
        int oheight = f.imageHeight;
        // 对截取的帧进行等比例缩放
        int width = 800;
        int height = (int) (((double) width / owidth) * oheight);
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage fecthedImage = converter.getBufferedImage(f);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                0, 0, null);
        File targetFile = new File(framefile);
        ImageIO.write(bi, "jpg", targetFile);
        //ff.flush();
        ff.stop();
    }
}
