package cn.com.ctop.crawler.modules.core.util;

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

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;

public class FfmpegUtils {
    public static String getVideoFirstImage(String url,int frame){
        try {
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(url);
            ff.start();
            int lenght = ff.getLengthInFrames();
            int i = 0;
            Frame f = null;
            while (i < lenght) {
// 过滤前5帧，避免出现全黑的图片，依自己情况而定
                f = ff.grabFrame();
                if ((i > frame) && (f.image != null)) {
                    break;
                }
                i++;
            }
            int owidth = f.imageWidth;
            int oheight = f.imageHeight;
            Java2DFrameConverter converter =new Java2DFrameConverter();
            BufferedImage fecthedImage =converter.getBufferedImage(f);
            // 对截取的帧进行等比例缩放
            int width = 800;
            int height = (int) (((double) width / owidth) * oheight);
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
            bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    0, 0, null);
            //io流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            //转换成字节
            byte[] bytes = baos.toByteArray();
            //转换成base64串
            String pngBase64 = Base64.getEncoder().encodeToString(bytes).trim();
            //删除 \r\n
            pngBase64 = pngBase64.replaceAll("\n", "").replaceAll("\r", "");
            baos.close();
            ff.close();
            return pngBase64;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
