Lately I have dedicated a little more time to developing an electron app which saves a frame of every video it encounters as PNG images:
Believe it or not the code to turn a frame of a video into an image element is not terribly complicated. Below is a simple function that can be used to get the an image element corresponding to a specific frame in a video:
This getVideoImage()
function takes three arguments:
path
{string}:
The path to the video. In the case that you are using this code in a web page this must be a video within the same domain.secs
{number | function(duration
): number}:
If this is a non-negative number this will indicate the time of the frame to capture in seconds. If this is a negative number this will indicate the time of the frame from the end of the video to capture in seconds. If this is a function it will be passed the duration as anumber
and the return value should be a number (positive or negative) which indicates the time of the frame that should be captured.callback
{function(img
,currentTime
,event
)}:
The function which is called either after loading the frame’s image successfully or after getting an error. The first argument passed will be theImage
object that is created (if no error occurred). The second argument passed will be the actual time in seconds used to pull the frame’s image (if no error occurred).
The third argument will either be aseeked
event or anerror
event.
This function can be used as is or can be modified. It is important to note that unless the video is in the exact same domain as the web page this code will NOT work due to the canvas being tainted. You can paste the following code into the code editor on this W3Schools sandbox page to see an example of getting multiple frames:
Let me know if you have any questions or suggestions and as usual, enjoy the free code! 😎
4 Comments
Louis · October 21, 2017 at 10:00 AM
Hi, thanks for the post!
I didn’t have a problem running the code on W3Schools, but when I created an index.html and run locally, i encountered an error with this line:
img.src = canvas.toDataURL();
error:
Uncaught DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported.
mansur · January 31, 2018 at 7:11 AM
How can get image from multiple video as like your screenshot?
Adrian Wong · October 1, 2018 at 2:20 PM
FWIW I extended this snippet to extract multiple frames/timestamps from the same video/canvas elements
https://gist.github.com/atwong/49b9e7d911dca0663e23c50c60f28784
Michael Köng · September 5, 2019 at 12:45 PM
Hi, works fine for chrome but safari doesn’t capture any frame. Any idea why?