java

Java擷取影片第一幀返回InputStream,用於影片上傳後作為封面


引入maven依賴

<dependency>
	<groupId>org.bytedeco</groupId>
	<artifactId>javacv-platform</artifactId>
	<version>1.5.1</version>
</dependency>

獲取影片幀返回InputStream

public class getImgUtil {

    // 獲取要取得的幀數
    private static final int fifthFrame= 5;

    /**
     * @param InputStream  需要擷取幀的影片的位元組輸入流
     *
     * @return 
     */
    public static InputStream getImg(InputStream is) {
        FFmpegFrameGrabber grabber;
        InputStream img=null ;
        try {
            grabber = new FFmpegFrameGrabber(is);

            grabber.start();
            // 影片總幀數
            int videoLength = grabber.getLengthInFrames();

            Frame frame = null;
            int i = 0;
            while (i < videoLength) {
                // 過濾前5幀,因為前5幀可能是全黑的
                frame = grabber.grabFrame();
                if ((i > fifthFrame) && (frame.image != null)) {
                    break;
                }
                i++;
            }

            2DFrameConverter converter = new 2DFrameConverter();
            // 繪製圖片
            BufferedImage bi = converter.getBufferedImage(frame);
            img = bufferedImageToInputStream(bi);
            
            grabber.stop();
            grabber.close();
          

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.err.println(img.toString());
        return img;
    }
    /**
	 * 將BufferedImage轉換為InputStream
	 * @param image
	 * @return
	 */
	public static InputStream bufferedImageToInputStream(BufferedImage image){
	    ByteArrayOutputStream os = new ByteArrayOutputStream();
	    try {
	        ImageIO.write(image, "png", os);
	        InputStream input = new ByteArrayInputStream(os.toByteArray());
	        return input;
	    } catch (IOException e) {
	    	
	    }
	    return null;
	}

本文章已修改原文用詞符合繁體字使用者習慣使其容易閱讀

版權宣告:此處為CSDN博主「李白嗯」的原創文章,依據CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。

原文連結:https://blog.csdn.net/u010210963/article/details/107457254