1. 程式人生 > >前端實現 視訊封面的擷取

前端實現 視訊封面的擷取

部分html

<video id="ppVideo" controls width="300" heigth="300" 
controlslist="nodownload" 
src="/xxx/xxx.mp4">您的瀏覽器不支援 video 標籤。</video>

<button type="button" id="interception">獲取視訊封面</button>

<img id="VideoPoster" src="">

js

$('#interception').on('click',function(){
       var video = $('#ppVideo').get(0);
       if (video.currentTime <= 0) {
           alert('請播放視訊,在合適的位置點選該按鈕');
           return;
       }
       var scale = 0.25;//比例
       var canvas = document.createElement("canvas");//建立一個畫布物件
       canvas.width = video.videoWidth * scale;//封面圖片的寬採用視訊寬度的0.25倍
       canvas.height = video.videoHeight * scale;//同上
       canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);//生成圖片
       $('#VideoPoster').attr('src', canvas.toDataURL());//設定圖片的base64格式資料流
       
})

html的變化

<img id="VideoPoster" src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAUAAAAC0CAYAAADl5PURAAAY1
UlEQVR4Xu2d6ZLbSA6EJfm3vTOe939TW9pgq9lNFkUmsoC6qH
TExsY0UQeygE9g8br+/PnrcblcLtfrdfq/y+Px8Z9f/+a/z39
Ij6+MF/2kf+/lv3/cfvQylZfzuN6e66B/rxV43JP4JPX68+dP
U2mt8ff3/jdknihfQwYJ7KT2fK8CYODqBXQlAB6LKAByQVYbK
Nzstta15/sFwLkKHL0CtP7C............很長省略
</img>

非常簡單,這樣就得到了視訊封面,想要上傳到伺服器就把base64資料流取出來處理就行了,下面是C#方式處理

public string SaveBase64ToImage()
{
   string base64 = Context.Request["base64"] ?? "";//前端傳過來的base64資料流
   string imgbase64 = base64.Substring(base64.IndexOf(",") + 1);//過濾掉逗號前面的部分,包括逗號
   Guid guid = new Guid();
   guid = Guid.NewGuid();
   var imgName = guid.ToString();//用Guid當做圖片檔案的名稱
   string filename = "";
   Bitmap bitmap = null;
   try
   {
        byte[] arr = Convert.FromBase64String(imgbase64);
        System.IO.MemoryStream ms = new System.IO.MemoryStream(arr);
        Bitmap bmp = new Bitmap(ms);
        ms.Close();//關閉當前流
        bitmap = bmp;
        filename = "Files/video/" + imgName + ".png";//所要儲存的相對路徑及名字              
        var path =  Context.Server.MapPath("/");//獲取專案的完整路徑
        string imgUrl = (path + filename).Replace("\\", "/"); //得到最終上傳路徑 
        bitmap.Save(imgUrl , System.Drawing.Imaging.ImageFormat.Png);//儲存到伺服器
    }
    catch (Exception e)
    {

    }
    return filename;//返回相對路徑
}