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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/238857.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

elementUI实现根据屏幕大小自适应换行,栅格化布局

需求&#xff1a; 默认一行展示4个卡片&#xff1b;当屏幕小于某个大小的时候&#xff0c;一行展示3个卡片&#xff1b;再小就展示2个&#xff1b;以此类推&#xff0c;最小就展示1个。 效果卡片样式如下图&#xff1a; 默认一行4个 屏幕缩小到某个阈值&#xff0c;一行展示…

苍穹外卖——删除购物车信息

1. 删除购物车中一个商品 1.1 产品原型 1.2 接口设计 1.3 数据模型 shopping_cart表&#xff1a; -- auto-generated definition create table shopping_cart (id bigint auto_increment comment 主键primary key,name varchar(32) null comment 商品名称…

oracle impdp 导入元数据表空间异常增大的解决办法

expdp导出的时候指定了contentsmetadata_only只导出元数据&#xff0c;但是在impdp导入到新库的时候&#xff0c;发现新库的表空间增长非常大&#xff0c;其实这个直接就可以想到&#xff0c;应该是大表的initial segment过大导致的 正常impdp&#xff0c;在执行创建表和索引的…

Nginx反向代理

nginx反向代理的好处 提高访问速度 因为nginx本身可以进行缓存&#xff0c;如果访问的同一接口&#xff0c;并且做了数据缓存&#xff0c;nginx就直接可把数据返回&#xff0c;不需要真正地访问服务端&#xff0c;从而提高访问速度。进行负载均衡 所谓负载均衡,就是把大量的请求…

VSC++=》 拆解整数对号入座重组

void 拆解整数对号入座重组(int& 数, bool 选 true) {int 对号[10]{}, j 选 ? 9 : 0, 反 0, 基 1;while (数)对号[数 % 10], 数 / 10;if (选)while (j > 0)if (对号[j])数 * 10, 数 j, (反 ? 基 * 10 : 0), 反 基 * j, --对号[j]; else --j;else while (j < …

golang Pool实战与底层实现

使用的go版本为 go1.21.2 首先我们写一个简单的Pool的使用代码 package mainimport "sync"var bytePool sync.Pool{New: func() interface{} {b : make([]byte, 1024)return &b}, }func main() {for j : 0; j < 10; j {obj : bytePool.Get().(*[]byte) // …

DAPP开发【04】测试驱动开发

测试驱动开发(Test Driven Development)&#xff0c;是一种不同于传统软件开发流程的新型的开发方法。它要求在编写某个功能的代码之前先编写测试代码&#xff0c;然后只编写使测试通过的功能代码通过测试来推动整个开发的进行。这有助于编写简洁可用和高质量的代码&#xff0c…

通义千问 模型学习 和 SDK试用

通义千问-14B-Chat-Int4 模型库 (modelscope.cn) **通义千问-14B&#xff08;Qwen-14B&#xff09;**是阿里云研发的通义千问大模型系列的140亿参数规模的模型。Qwen-14B是基于Transformer的大语言模型, 在超大规模的预训练数据上进行训练得到。预训练数据类型多样&#xff0…

项目实战之RabbitMQ冗余双写架构

&#x1f9d1;‍&#x1f4bb;作者名称&#xff1a;DaenCode &#x1f3a4;作者简介&#xff1a;啥技术都喜欢捣鼓捣鼓&#xff0c;喜欢分享技术、经验、生活。 &#x1f60e;人生感悟&#xff1a;尝尽人生百味&#xff0c;方知世间冷暖。 &#x1f4d6;所属专栏&#xff1a;项…

SQL-分页查询offset的用法

今天在做一道关于查询一张表中第二高工资的问题时发现没有思路&#xff0c;经过一番搜索发现需要用到offset偏移量来解决这个问题。 OFFSET关键字用于指定从结果集的哪一行开始返回数据。通常&#xff0c;它与LIMIT一起使用&#xff0c;以实现分页效果。其语法如下&#xff1a…

行内元素和块级元素分别有哪些?有何区别?怎样转换?

行内元素和块级元素分别有哪些&#xff1f; 常见的块级元素&#xff1a; p、div、form、ul、li、ol、table、h1、h2、h3、h4、h5、h6、dl、dt、dd 常见的行级元素&#xff1a; span、a、img、button、input、select 有何区别&#xff1f; 块级元素&#xff1a; 总是在新行上…

mac 系统 vmware 安装centos8

选择镜像 安装系统 依次设置有告警的项目 设置用户名密码 设置root密码 重启系统 重启成功进入下面界面 勾选&#xff0c;点击done 点击箭头所指按钮 输入密码登录 安装成功了 设置网络 打开终端 切换root用户 输入下面指令 su root 输入root的密码 安装git