Scenario: When the video is displayed after uploading the video in the business, a cover image needs to be displayed on the video
The poster attribute in the tag vedio specifies the image displayed when the video is downloaded, or the image displayed before the user clicks the play button
Target:
<video
controls
:poster="CoverImg">
<source :src="item.FileUrl" type="video/mp4" />
您的浏览器不支持 HTML5 video 标签。
</video>
Capture the first frame of the video as the cover image
// 截取视频第一帧作为封面图 然后转成base64
getVideoBase64(url) {
return new Promise(function (resolve) {
let dataURL = "";
const video = document.createElement("video");
video.setAttribute("crossOrigin", "anonymous"); // 处理跨域
video.setAttribute("src", url);
video.setAttribute("preload", "auto");
video.addEventListener("loadeddata", function () {
const canvas = document.createElement("canvas");
console.log("video.clientWidth", video.videoWidth); // 视频宽
console.log("video.clientHeight", video.videoHeight); // 视频高
const width = video.videoWidth || 400; // canvas的尺寸和图片一样
const height = video.videoHeight || 240; // 设置默认宽高为 400 240
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(video, 0, 0, width, height); // 绘制canvas
dataURL = canvas.toDataURL("image/jpeg"); // 转换为base64
resolve(dataURL);
});
});
},
Convert base64 to image file
// base64转图片
getFileFromBase64(base64URL, filename) {
var arr = base64URL.split(","),
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: "image/png" });
},
upload video
<input
type="file"
v-show="inputShow"
ref="inputImg"
@change="preview($event)"
/>
Specific process
preview(event) {
var file = event.target.files[0];
let ContentType;
console.log(file);
if (file.type.includes("image")) {
ContentType = "image";
} else if (file.type.includes("application")) {
ContentType = "file";
} else if (file.type.includes("video")) {
ContentType = "video";
} else {
ContentType = "file";
}
const fd = new FormData(); // FormData 对象
fd.append("Files", file); // 文件对象
//拿到视频文件请求后端接口
uploads(fd).then(async (res) => {
if (res.Code == "0") {
//如果文件类型是video就进行转化
if (ContentType == "video") {
//截取视频第一帧
const vedioUrl = await this.getVideoBase64(res.Urls[0]);
// 拿到视频第一帧的base64图片转成图片文件
const imgUrl = await this.getFileFromBase64(vedioUrl, "kefu.jpeg");
const fd1 = new FormData();
//拿到图片文件请求后端接口返回链接
fd1.append("Files", imgUrl);
// 封面图
this.CoverImg = await uploads(fd1);
console.log("this.CoverImg", this.CoverImg);
}
}