Search code examples
javaclojureopentype

Generating Image in Java/Clojure containing text that uses OpenType Features


I am trying to generate an image using Java/Clojure made up mainly of text that uses a custom font with opentype features. I have tried to use the current OTF Font support in Java even upgraded to oracle Java 8 and set the TextAttribute Ligatures to On but to no help. Can anyone provide suggestions on what is possible.

Note I need the ability to determine font-size, line-height and width of image so I am not sure if using TEX is possible in that situation.


Solution

  • I believe the answer for the Java side was answered in this SO question. But I did a translation to Clojure because java interop gets a bit tricky. Notice that ImageIO/write takes the BufferedImage instance not the Graphics2D, throughout the program image gets mutated using an instance of Graphics2D.

    (ns so-33725486.core
      (:import [java.awt Graphics2D Color Font]
               [java.awt.image BufferedImage]
               [javax.imageio ImageIO]
               [java.io File]))
    
    (defn str->img [string filename]
      (let [file (File. (str "./" filename ".png"))
            width 250
            height 100
            image (BufferedImage. width height BufferedImage/TYPE_INT_ARGB)
            graphics (.createGraphics image)
            font-size 30
            font (Font. "TimesRoman" Font/BOLD font-size)]
        (.setColor graphics Color/BLACK)
        (.setFont graphics font)
        (.drawString graphics string 10 25)
        (ImageIO/write image "png" file)))