uniapp 视频截图

uniapp 视频截图

本文只针对微信小程序,其他平台并没有测试过,不确定可行性。

微信提供了两个组件可以用来播放视频:

  • live-player: 只要用于实时音视频的播放(出于政策和合规的考虑,微信暂时没有放开所有小程序对<live-player> 标签的支持,具体可以查看官方文档)。
  • video: 播放视频。

使用live-player组件来截图

LivePlayerContext 实例上有一个snapshot方法,可以调用进行截图。

示例伪代码:

<live-player id="myVideo" src="xxxx" :autoplay="isPlay" mode="live"></live-player>
// 获取live-player上下文对象
const ctx = wx.createLivePlayerContext('#myVideo');
ctx.play({
    
    
    success: () => {
    
    
        // 确保视频播放成功才进行截图
        ctx.snapshot({
    
    
			success: res => {
    
    
				wx.saveImageToPhotosAlbum({
    
    
			        filePath: res.tempImagePath,
			        success: () => {
    
    
	    	    		console.log('save success');
	    	    	},
		    	    fail: () => {
    
    
    		    		console.log('save fail');
	        		},
		        })  
			},
			fail: () => {
    
    
				console.log('snapshot fail');
			}
		})
    }
});

上面的伪代码介绍了如何截图,以及把截图保存在手机上。

使用video组件来截图

video组件本身提供了一个控件(show-snapshot-button)去帮助我们截图,不过只有在全屏状态下才会把这个控件展示出来,查看官方文档

<video id="myVideo" style="width: 100%;height: 200px"
  src="http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400"
  object-fit="fill" show-snapshot-button controls />

从下图可以看到右侧有个相机图标,点击即可截图并下载到手机。

请添加图片描述

请添加图片描述

不过对于非全屏状态下,截图控件并不会展示,而且VideoContext对象也没有暴露出截图的方法。

使用canvas

虽然VideoContext对象没有提供截图的方法,在非全屏状态没法截图,但是我们也可以使用canvas来手动实现一个截图方法。

<video id="myVideo" style="width: 100%;height: 200px"
	src="http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400"
	object-fit="fill" show-snapshot-button controls />
<canvas id="hiddenCanvas" style="width: 100%; height: 200px;" type="2d" canvas-id="circleCanvas"></canvas>
<button @tap="snapshot">截图</button>

此时页面效果如下所示

在这里插入图片描述

// 获取video上下文
const getVideoContext = (id, instance) => {
    
    
		const query = uni.createSelectorQuery().in(instance);
		const queryVideo = query.select(`#${
      
      id}`).context();
		return new Promise((resolve, reject) => {
    
    
			queryVideo.exec(res => {
    
    
				resolve(res);
			});
		});
	}

async record() {
    
    
    const query = wx.createSelectorQuery()
    query.select('#hiddenCanvas')
        .fields({
    
    
            node: true,
            size: true
        })
        .exec(async (res) => {
    
    
            const canvas = res[0].node;
            const dpr = uni.getSystemInfoSync().pixelRatio
            canvas.width = res[0].width * dpr // 获取宽
            canvas.height = res[0].height * dpr // 获取高
            const ctx = canvas.getContext('2d');
            ctx.scale(dpr, dpr)
            const video = await getVideoContext('myVideo', this);
            console.log(video)
            ctx.drawImage(video[0].context, 0, 0);
        })
}

请添加图片描述

我们加上保存的办法

async record() {
    
    
    const query = wx.createSelectorQuery()
    query.select('#hiddenCanvas')
        .fields({
    
    
            node: true,
            size: true
        })
        .exec(async (res) => {
    
    
            const canvas = res[0].node;
            const dpr = uni.getSystemInfoSync().pixelRatio
            canvas.width = res[0].width * dpr // 获取宽
            canvas.height = res[0].height * dpr // 获取高
            const ctx = canvas.getContext('2d');
            ctx.scale(dpr, dpr)
            const video = await getVideoContext('myVideo', this);
            console.log(video)
            ctx.drawImage(video[0].context, 0, 0);
            // 从canvas获取图片像素数据
			const imgData = canvas.toDataURL('image/png');
			this.saveImage(imgData);
        })
}

function saveImage(url) {
    
    
    let base64 = url.replace(/^data:image\/\w+;base64,/, ""); //去掉data:image/png;base64,
    let filePath = wx.env.USER_DATA_PATH + '/video.png';
    uni.getFileSystemManager().writeFile({
    
    
        filePath: filePath, //创建一个临时文件名
    	data: base64,       //写入的文本或二进制数据
	    encoding: 'base64', //写入当前文件的字符编码
    	success: res => {
    
    
	    	console.log(res);
		    uni.saveImageToPhotosAlbum({
    
    
		        filePath: filePath,
    		    success: () => {
    
    
                    console.log('保存成功')
		    	},
			    fail: err => {
    
    
				    console.log('保存失败')
    			}
	    	})
        }
    })
}

现在点击截图就可以直接保存在手机上来。

可能我们不需要在页面上展示一个canvas,如果直接设置display:none来隐藏,会出现saveImageToPhotosAlbum:fail save fail:Error Domain=PHPhotosErrorDomain Code=3302 "(null)"错误,这时候可能使用position:absolute;,绝对定位后将整个canvas移出视图层(比如,然后指定left一个比较大的值,让canvas的显示超出屏幕范围)。

猜你喜欢

转载自blog.csdn.net/qq_42880714/article/details/132067332
今日推荐