当前位置: 首页 > news >正文

flutter开发实战-实现获取视频的缩略图封面video_thumbnail

flutter开发实战-实现获取视频的缩略图封面video_thumbnail

在很多时候,我们查看视频的时候,视频没有播放时候,会显示一张封面,可能封面没有配置图片,这时候就需要通过获取视频的缩略图来显示封面了。这里使用了video_thumbnail来实现获取视频的缩略图。

一、引入video_thumbnail

在工程的pubspec.yaml中引入插件

  # 视频缩略图video_thumbnail: ^0.5.3

VideoThumbnail的属性如下

static Future<String?> thumbnailFile({required String video,Map<String, String>? headers,String? thumbnailPath,ImageFormat imageFormat = ImageFormat.PNG,int maxHeight = 0,int maxWidth = 0,int timeMs = 0,int quality = 10}) 
  • thumbnailPath为本地存储的文件目录
  • imageFormat格式 jpg,png等
  • video视频地址
  • timeMs

二、获取视频的缩略图

使用video_thumbnail来获取视频缩略图

定义视频缩略图信息

class VideoThumbInfo {String url; // 原视频地址File? thumbFile; // 缩略图本地fileint? width; // 缩略图的widthint? height; // 缩略图的heightVideoThumbInfo({required this.url,});
}

获取视频缩略图本地File

String path = (await getTemporaryDirectory()).path;String thumbnailPath = path + "/${DateTime.now().millisecond}.jpg";final fileName = await VideoThumbnail.thumbnailFile(video:"https://vd2.bdstatic.com/mda-maif0tt1rirqp27q/540p/h264_cae/1611052585/mda-maif0tt1rirqp27q.mp4",thumbnailPath: thumbnailPath,imageFormat: imageFormat,quality: quality,maxWidth: maxWidth,maxHeight: maxHeight,timeMs: timeMs,);File file = File(thumbnailPath);

获取缩略图的宽高

Image image = Image.file(thumbFile!);image.image.resolve(const ImageConfiguration()).addListener(ImageStreamListener((ImageInfo imageInfo, bool synchronousCall) {int imageWidth = imageInfo.image.width;int imageHeight = imageInfo.image.height;VideoThumbInfo videoThumbInfo = VideoThumbInfo(url: url);videoThumbInfo.thumbFile = thumbFile;videoThumbInfo.width = imageWidth;videoThumbInfo.height = imageHeight;VideoThumb.setThumbInfo(url, videoThumbInfo);onVideoThumbInfoListener(videoThumbInfo);},onError: (exception, stackTrace) {print("getVideoThumbInfoByFile imageStreamListener onError exception:${exception.toString()},stackTrace:${stackTrace}");onVideoThumbInfoListener(null);},),);

完整代码如下

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_thumbnail/video_thumbnail.dart';// ignore: non_constant_identifier_names
VideoThumbManager get VideoThumb => VideoThumbManager.instance;class VideoThumbManager {static VideoThumbManager get instance {return _singleton;}//保存单例static VideoThumbManager _singleton = VideoThumbManager._internal();//工厂构造函数factory VideoThumbManager() => _singleton;//私有构造函数VideoThumbManager._internal();// 保存url对应的本地缩略图filefinal _thumbMap = Map<String, File>();// url对应本地缩略图的信息final _thumbInfoMap = Map<String, VideoThumbInfo>();Future<void> setThumb(String url, File file) async {if (url.isEmpty) {return;}bool exist = await file.exists();if (exist == false) {return;}_thumbMap[url] = file;}Future<File?> getThumb(String url, {ImageFormat imageFormat = ImageFormat.JPEG,int maxHeight = 0,int maxWidth = 0,int timeMs = 0,int quality = 100,}) async {File? thumbFile = _thumbMap[url];if (thumbFile != null) {return thumbFile;}String path = (await getTemporaryDirectory()).path;String thumbnailPath = path + "/${DateTime.now().millisecond}.jpg";final fileName = await VideoThumbnail.thumbnailFile(video:"https://vd2.bdstatic.com/mda-maif0tt1rirqp27q/540p/h264_cae/1611052585/mda-maif0tt1rirqp27q.mp4",thumbnailPath: thumbnailPath,imageFormat: imageFormat,quality: quality,maxWidth: maxWidth,maxHeight: maxHeight,timeMs: timeMs,);File file = File(thumbnailPath);setThumb(url, file);return file;}// 获取缩略图的大小void getVideoThumbInfo(String url, {ImageFormat imageFormat = ImageFormat.JPEG,int maxHeight = 0,int maxWidth = 0,int timeMs = 0,int quality = 100,required Function(VideoThumbInfo?) onVideoThumbInfoListener,}) async {try {VideoThumbInfo? thumbInfo = VideoThumb.getThumbInfo(url);if (thumbInfo != null) {onVideoThumbInfoListener(thumbInfo);return;}await VideoThumb.getThumb(url,imageFormat: imageFormat,maxWidth: maxWidth,maxHeight: maxHeight,timeMs: timeMs,quality: quality,).then((value) {File? thumbFile = value;if (thumbFile != null) {VideoThumb.getVideoThumbInfoByFile(url: url,thumbFile: thumbFile,onVideoThumbInfoListener: onVideoThumbInfoListener,);} else {onVideoThumbInfoListener(null);}}).onError((error, stackTrace) {print("getVideoThumbInfo error:${error.toString()}");onVideoThumbInfoListener(null);}).whenComplete(() {print("getVideoThumbInfo whenComplete");});} catch (e) {print("getVideoThumbInfo catch error:${e.toString()}");onVideoThumbInfoListener(null);}}/// 根据file获取缩略图信息void getVideoThumbInfoByFile({required String url,required File thumbFile,required Function(VideoThumbInfo?) onVideoThumbInfoListener,}) async {try {VideoThumbInfo? thumbInfo = VideoThumb.getThumbInfo(url);if (thumbInfo != null) {onVideoThumbInfoListener(thumbInfo);return;}Image image = Image.file(thumbFile!);image.image.resolve(const ImageConfiguration()).addListener(ImageStreamListener((ImageInfo imageInfo, bool synchronousCall) {int imageWidth = imageInfo.image.width;int imageHeight = imageInfo.image.height;VideoThumbInfo videoThumbInfo = VideoThumbInfo(url: url);videoThumbInfo.thumbFile = thumbFile;videoThumbInfo.width = imageWidth;videoThumbInfo.height = imageHeight;VideoThumb.setThumbInfo(url, videoThumbInfo);onVideoThumbInfoListener(videoThumbInfo);},onError: (exception, stackTrace) {print("getVideoThumbInfoByFile imageStreamListener onError exception:${exception.toString()},stackTrace:${stackTrace}");onVideoThumbInfoListener(null);},),);} catch (e) {print("getVideoThumbInfoByFile catch error:${e.toString()}");onVideoThumbInfoListener(null);}}void removeThumb(String url) {if (url.isEmpty) {return;}_thumbMap.remove(url);}/// 获取存储缩略图信息VideoThumbInfo? getThumbInfo(String url) {if (url.isEmpty) {return null;}VideoThumbInfo? thumbInfo = _thumbInfoMap[url];return thumbInfo;}/// 存储缩略图信息void setThumbInfo(String url, VideoThumbInfo videoThumbInfo) async {if (url.isEmpty) {return;}_thumbInfoMap[url] = videoThumbInfo;}void removeThumbInfo(String url) {if (url.isEmpty) {return;}_thumbInfoMap.remove(url);}void clear() {_thumbMap.clear();_thumbInfoMap.clear();}
}class VideoThumbInfo {String url; // 原视频地址File? thumbFile; // 缩略图本地fileint? width; // 缩略图的widthint? height; // 缩略图的heightVideoThumbInfo({required this.url,});
}

三、显示视频缩略图的Widget

用于显示视频缩略图的Widget

/// 用于显示视频缩略图的Widget
class VideoThumbImage extends StatefulWidget {const VideoThumbImage({super.key, required this.url, this.maxWidth, this.maxHeight});final String url;final double? maxWidth;final double? maxHeight;@overrideState<VideoThumbImage> createState() => _VideoThumbImageState();
}class _VideoThumbImageState extends State<VideoThumbImage> {VideoThumbInfo? _videoThumbInfo;@overridevoid initState() {// TODO: implement initStatesuper.initState();VideoThumb.getVideoThumbInfo(widget.url,onVideoThumbInfoListener: (VideoThumbInfo? thumbInfo) {if (mounted) {setState(() {_videoThumbInfo = thumbInfo;});}});}@overridevoid dispose() {// TODO: implement disposesuper.dispose();}// 根据VideoThumb来显示图片Widget buildVideoThumb(BuildContext context) {if (_videoThumbInfo != null && _videoThumbInfo!.thumbFile != null) {double? imageWidth;double? imageHeight;if (_videoThumbInfo!.width != null && _videoThumbInfo!.height != null) {imageWidth = _videoThumbInfo!.width!.toDouble();imageWidth = _videoThumbInfo!.height!.toDouble();}return Container(width: imageWidth,height: imageHeight,clipBehavior: Clip.hardEdge,decoration: const BoxDecoration(color: Colors.transparent,),child: Image.file(_videoThumbInfo!.thumbFile!,width: imageWidth,height: imageHeight,),);}return Container();}@overrideWidget build(BuildContext context) {return ConstrainedBox(constraints: BoxConstraints(maxWidth: widget.maxWidth ?? double.infinity,maxHeight: widget.maxHeight ?? double.infinity,),child: buildVideoThumb(context),);}
}

效果图如下:

在这里插入图片描述

四、小结

flutter开发实战-实现获取视频的缩略图封面video_thumbnail

学习记录,每天不停进步。

相关文章:

  • 主机安全-WindowsLinux的SSH安全加固
  • 解锁 ElasticJob 云原生实践的难题
  • 有权图的最短路径算法
  • 快速筛出EXCEL行中的重复项
  • Android flutter项目 启动优化实战(一)使用benchmark分析项目
  • SQL Server 2016(分离和附加数据库)
  • P1 什么是链表 C语言简单易懂
  • MOS管的静电击穿问题
  • 2023年12月03日新闻简报(国内国际)
  • 机器学习中参数优化或交叉验证评估指标含义
  • ASP.NET Core 使用IIS调试出现505.24错误
  • 软件工程 - 第8章 面向对象建模 - 4 - 物理体系结构建模
  • 【C语言:数据在内存中的存储】
  • CSS 选择器优先级,!important 也会被覆盖?
  • Python与设计模式--模板模式
  • 【css3】浏览器内核及其兼容性
  • Android开源项目规范总结
  • JavaSE小实践1:Java爬取斗图网站的所有表情包
  • mysql_config not found
  • Netty 4.1 源代码学习:线程模型
  • swift基础之_对象 实例方法 对象方法。
  • text-decoration与color属性
  • Web Storage相关
  • 人脸识别最新开发经验demo
  • 使用 @font-face
  • 优化 Vue 项目编译文件大小
  • AI又要和人类“对打”,Deepmind宣布《星战Ⅱ》即将开始 ...
  • Unity3D - 异步加载游戏场景与异步加载游戏资源进度条 ...
  • ​html.parser --- 简单的 HTML 和 XHTML 解析器​
  • # 透过事物看本质的能力怎么培养?
  • #Java第九次作业--输入输出流和文件操作
  • #QT项目实战(天气预报)
  • #我与Java虚拟机的故事#连载16:打开Java世界大门的钥匙
  • $.ajax中的eval及dataType
  • (1)bark-ml
  • (3)选择元素——(17)练习(Exercises)
  • (pt可视化)利用torch的make_grid进行张量可视化
  • (带教程)商业版SEO关键词按天计费系统:关键词排名优化、代理服务、手机自适应及搭建教程
  • (力扣)1314.矩阵区域和
  • (十五)Flask覆写wsgi_app函数实现自定义中间件
  • (四)搭建容器云管理平台笔记—安装ETCD(不使用证书)
  • (转)德国人的记事本
  • ***通过什么方式***网吧
  • .NET CLR基本术语
  • .NET 中 GetProcess 相关方法的性能
  • .net6 webapi log4net完整配置使用流程
  • .NETCORE 开发登录接口MFA谷歌多因子身份验证
  • .net之微信企业号开发(一) 所使用的环境与工具以及准备工作
  • [ linux ] linux 命令英文全称及解释
  • [ Linux 长征路第五篇 ] make/Makefile Linux项目自动化创建工具
  • []我的函数库
  • [20170728]oracle保留字.txt
  • [ABC294Ex] K-Coloring
  • [AutoSar]工程中的cpuload陷阱(三)测试
  • [AX]AX2012 R2 出差申请和支出报告