[Windows 8] How to take screenshots of a video?
August 30th, 2012 | Posted by in .NET | Article | HTML5 | Windows 8 | WinJS | WinRT | Read: 701Sometimes, it’s useful/needed to take screenshots of a video that is played by your application. Here is a simple (but working) technique to perform this task:
<section class="section"> <p> <button id="btnVideoSelect">Select Video</button> </p> <p> <video id="videoPreview" width="350" height="250"></video> </p> </section> <section class="section2"> <div id="outputListView" class="output" data-win-control="WinJS.UI.ListView"></div> </section>
var screenshots = new WinJS.Binding.List(); var openPicker = new Windows.Storage.Pickers.FileOpenPicker(); openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.list; openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.musicLibrary; openPicker.fileTypeFilter.replaceAll([".mp4", ".mpeg", ".avi"]); openPicker.pickSingleFileAsync().done(function(file) { if (file) { var videoPreview = document.getElementById("videoPreview"); if(videoPreview) { var fileLocation = window.URL.createObjectURL(file); videoPreview.src = fileLocation; videoPreview.setAttribute("controls", "true"); var createScreenshots = false; videoPreview.addEventListener("ended", function() { createScreenshots = false; }); videoPreview.addEventListener("play", function () { createScreenshots = true; setInterval(function () { if (createScreenshots) { var canvas = document.createElement("canvas"); if (canvas) { canvas.width = videoPreview.videoWidth; canvas.height = videoPreview.videoHeight; var ctx = canvas.getContext("2d"); ctx.drawImage(videoPreview, 0, 0, videoPreview.videoWidth, videoPreview.videoHeight); var imageUrl = canvas.toDataURL(); screenshots.push({ url: imageUrl, width: 150, height: 50 }); } } }, 500); }); videoPreview.play(); } } });
Let’s take a look at the code now ! First, we use a FileOpenPicker to allow users to select the video to use. Once a video is selected, we set it a the source of the Video element. Then, as soon as the video starts to play, we create a Canvas element and access to the 2D context, that will allow us to call the drawImage method. This method accept, as a parameter, the video element that we use to play the video!
Finally, once the screenshot is generated, we use the method toDataURL to get its content encoded in Base64 and put it in a Binding list, which allows the ListView to be notified when new items are added !
As a result, take a look at this image!
This is just a prototype (code could be better) but you get the main idea! Of course, you could also use this code to get the screenshot at a particular time of the video (like if you wanted to extract a particular frame from the video).
Happy coding!
You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.





Pingback: Windows 8 Developer Links – 2012-08-31Dan Rigby | Dan Rigby