public static String randomGrabberFFmpegImage(String videoFilePath, String targetDirPath, String imageFileName){
try {
FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(videoFilePath);
frameGrabber.start();
Frame keyFrame = frameGrabber.grabKeyFrame();
// 看一下是否需要旋转
Frame rotateFrame = rotateFrame(frameGrabber, keyFrame);
Java2DFrameConverter java2DFrameConverter = new Java2DFrameConverter();
BufferedImage bufferedImage = java2DFrameConverter.convert(rotateFrame==null ? keyFrame : rotateFrame);
frameGrabber.stop();
File file = writeFile(bufferedImage, imageFileName,targetDirPath);
if (file != null && file.exists()) {
return file.getAbsolutePath();
}
} catch (Exception e) {
log.error("抓图发生错误", e);
}
return null;
}
private static Frame rotateFrame(FFmpegFrameGrabber frameGrabber, Frame frame) {
//获取旋转角度信息(90度)
String rotate = frameGrabber.getVideoMetadata("rotate");
if(null != rotate && rotate.length() > 1) {
try {
int angle = Integer.parseInt(rotate);
log.info("抓图片开始,旋转角度:{}", angle);
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
IplImage src = converter.convert(frame);
return converter.convert(rotate(src, angle));
}
catch (Exception e) {
log.error("旋转图片发生错误", e);
}
}
return null;
}
private static File writeFile(BufferedImage bufferedImage, String imageFileName, String targetDirPath) {
if (null == bufferedImage) {
return null;
}
String imageMat = getImageMat();
String fileName = imageFileName + "." + imageMat;
String filePath = targetDirPath + File.separator + fileName;
log.info("输出图片:{}", filePath);
File output = new File(filePath);
try {
if (isCompressImage()) {
BufferedImage thumb = thumbnail(bufferedImage, 50);
ImageIO.write(thumb, imageMat, output);
}
else{
ImageIO.write(bufferedImage, imageMat, output);
}
}catch (IOException e) {
log.error("压缩输出图片发生错误", e);
}
return output;
}
/*
* 旋转角度的
*/
public static IplImage rotate(IplImage src, int angle) {
IplImage img = IplImage.create(src.height(), src.width(), src.depth(), src.nChannels());
opencv_core.cvTranspose(src, img);
opencv_core.cvFlip(img, img, angle);
return img;
}
/**
* 按照固定宽高原图压缩
* @param bufferedImage 图像源
* @param scale 缩放比例
* @return
*/
public static BufferedImage thumbnail(BufferedImage bufferedImage, int scale) {
if (scale > 100) {
scale = 100;
}
if (scale < 1) {
scale = 1;
}
int oriWidth = bufferedImage.getWidth();
int oriHeight = bufferedImage.getHeight();
int width = oriWidth * scale / 100;
int height = oriHeight * scale / 100;
log.info("压缩图片:原始大小{}*{},新尺寸:{}*{}", oriWidth, oriHeight, width, height);
Image image = bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = newImage.getGraphics();
graphics.setColor(Color.RED);
// 绘制处理后的图
graphics.drawImage(image, 0, 0, null);
graphics.dispose();
return newImage;
}
从视频中提取一张图片
最新推荐文章于 2024-05-29 09:53:04 发布