DEV Community

DCWizard
DCWizard

Posted on

Simple convert image to video

I needed something simple that would convert any image to a video. Couldn't find one that would just do that.
So, I study what the others have done and made that simple and clear version.

I'm working on a lot a stuff.
If you want to follow my stuff and/or support me.
You can check/register to my website:
https://thinknspeak.net/

For me this code is completely self-explanatory. If you have any questions. The comments are down below.

function ImageToVideo       (ThisImage, ThisCallBack, ThisDuration = 5000, ThisFps = 30){
  let ThisCanvas          = document.createElement("canvas"); 
  let ThisCtx             = ThisCanvas.getContext('2d');
  ThisCanvas.width        = ThisImage.width;
  ThisCanvas.height       = ThisImage.height;

  // NO NEED SINCE WE'RE DRAWING THE ENTIRE SURFACE.
  // ThisCtx.clearRect         (0, 0, ThisCanvas.width, ThisCanvas.height);
  ThisCtx.drawImage         (ThisImage, 0, 0, ThisCanvas.width, ThisCanvas.height);

  let TheseChunks         = new Set();  
  let VideoMimeType       = "video/webm";

  let VideoOptions        = {
    // audioBitsPerSecond:     128000,
    // videoBitsPerSecond:    2500000,
    mimeType: VideoMimeType
  };
  let ThiMediaStream      = ThisCanvas.captureStream(ThisFps);
  let ThisMediaRecorder   = new MediaRecorder(ThiMediaStream);

  ThisMediaRecorder.ondataavailable = (ThisEvent) => {
    TheseChunks.add(ThisEvent.data);
    console.warn("Video info", ThisEvent.data);
    VideoMimeType         = ThisEvent.data.type;
    if(IsFunction(ThisCallBack)){
      ThisCallBack (GetThisVideo(TheseChunks));
    }
  }
  ThisMediaRecorder.start();
  setTimeout(function       (){
    ThisMediaRecorder.stop();
  }, ThisDuration);
  function GetThisVideo     (ThisData){
    let ThisBlobOptions   = {
      type: VideoMimeType
    };
    let ThisBlob          = new Blob(ThisData, ThisBlobOptions);
    let ThisSrc           = URL.createObjectURL(ThisBlob);
    return { "blob":ThisBlob, "src":ThisSrc };
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)