在聖品上傳時每每須要生成一張預覽圖(縮略圖),若是在非特殊狀況下讓用戶單獨上傳,會形成工做壓力,此時能夠用視頻中某一幀做爲封面圖,實現方式以下: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); } }