Created
June 17, 2019 10:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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