Skip to content

Instantly share code, notes, and snippets.

@simongray
Created June 17, 2019 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simongray/f323a85778fb7e7bb836424c63aea0a0 to your computer and use it in GitHub Desktop.
Save simongray/f323a85778fb7e7bb836424c63aea0a0 to your computer and use it in GitHub Desktop.
Helper functions for converting a DataURL to an image and saving to a file
(defn dataurl->mime-type
"Extract the mime-type from a data URL."
[dataurl]
(->> (str/split dataurl #",")
(first)
(re-find #":(.*?);")
(second)))
(defn dataurl->image
"Extract the image data from a data URL."
[dataurl]
(let [data-str (second (str/split dataurl #","))
bytes (DatatypeConverter/parseBase64Binary data-str)]
(ImageIO/read (ByteArrayInputStream. bytes))))
;; Example - save image as file
(let [mime-type (dataurl->mime-type dataurl)
format (second (str/split mime-type #"/"))
image (dataurl->image dataurl)
out (File. (str "img." format))]
(ImageIO/write ^BufferedImage image ^String format out))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment