Friday, June 17, 2022

Creating videos with Clojure

After looking through the Java SE API we can safely say that it doesn't contain any support for creating videos. To do that we need an external library like JCodec. It has APIs for the two main Java client platforms: Java SE and Android. In order to demonstrate the building of videos in Clojure, I will be using the JCodec Java SE API, which allows us to make use of our existing Java 2D functions to easily create videos. By itself, the Java SE doesn't let us do that much so to do interesting things like creating videos we need to look to external APIs. JCodec is one such API that is readily available.
(ns video.core
  (:import (java.io File)
           (org.jcodec.api.awt AWTSequenceEncoder)
           (java.awt.image BufferedImage)
           (java.awt RenderingHints Color)))

(defn main
  []

  (let [file (File.
               (str
                 (System/getProperty "user.home")
                 "/Media/out.mp4"))
        encoder (AWTSequenceEncoder/createSequenceEncoder file 30)
        img (BufferedImage. 600 600 BufferedImage/TYPE_INT_RGB)
        g (.createGraphics img)]
    (.setRenderingHint g RenderingHints/KEY_ANTIALIASING RenderingHints/VALUE_ANTIALIAS_ON)

    (dotimes [i 300]
      (.setColor g Color/WHITE)
      (.fillRect g 0 0 600 600)

      (.setColor g Color/BLACK)
      (let [center 300
            size (* i 2)]
        (.drawOval g (- center (/ size 2)) (- center (/ size 2)) size size))

      (.encodeImage encoder img))

    (.finish encoder)))
This produces the following video:

No comments:

Post a Comment