Introduction:
In this article, you will learn how to get/capture image from videos using javascript.
When creating online apps in any programming language using javascript, it may occasionally be necessary to grab an image from a video.
You may learn how to extract an image from a video in this lesson. Create a single HTML file, and then use the video element to play a video. Create a js script to get/capture a picture from the video after that.
To extract an image from a video using JavaScript, follow these steps:
-Create HTML File
– Create Script to Get Image From Video
Step 1: Create HTML File
Create a new HTML file with .html extension and update the following code into your html file:
<video id="video" src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4" controls></video> <br> <button onclick="capture()">Capture</button> <br> <canvas id="canvas" style="overflow:auto"></canvas>
You can see the video tag for your web browser to play the video in the HTML file. Additionally, there is a button for using the javascript capture function to do the operation of taking a picture.
Step 2: Create Script to Get Image From Video
function capture() { var canvas = document.getElementById("canvas"); var video = document.querySelector("video"); canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas .getContext("2d") .drawImage(video, 0, 0, video.videoWidth, video.videoHeight); const playImage = new Image(); playImage.src = "path to image asset"; playImage.onload = () => { const startX = video.videoWidth / 2 - playImage.width / 2; const startY = video.videoHeight / 2 - playImage.height / 2; canvas .getContext("2d") .drawImage(playImage, startX, startY, playImage.width, playImage.height); canvas.toBlob() = (blob) => { const img = new Image(); img.src = window.URL.createObjectUrl(blob); }; }; } capture();
The basic procedure is to draw the current instance of the video element on the canvas, obtain the blob from canvas, and use that blob as the source for an image, or upload the blob straight to storage like AWS or another service.
OUTPUT: