Where to store your (image) files in Leiningen project, and how to fetch them?

less than 1 minute read

Notes

Create new app using:

$ lein new app image_in_resources

Place clojure_diary-logo.png in resources/images/ folder.

project.clj content:

(defproject image_in_resources "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
            :url "https://www.eclipse.org/legal/epl-2.0/"}
  :dependencies [[org.clojure/clojure "1.11.1"]]
  :main ^:skip-aot image-in-resources.core
  :target-path "target/%s"
  :profiles {:uberjar {:aot :all
                       :jvm-opts ["-Dclojure.compiler.direct-linking=true"]}})

src/image_in_resources/core.clj content:

(ns image-in-resources.core
  (:gen-class)
  (:require [clojure.java.io :as io])
  (:import [javax.imageio ImageIO]))

(defn load-image [image-name]
  (let [image-url (io/resource (str "images/" image-name))]
    (if image-url
      (ImageIO/read image-url)
      (throw (Exception. (str "Image not found: " image-name))))))

(defn save-image [image output-path]
  (ImageIO/write image "png" (io/file output-path)))

(defn -main []
  (let [image-name "clojure_diary_logo.png"
        output-path (str "./" image-name)] ; Save to current directory
    (try
      (let [img (load-image image-name)]
        (save-image img output-path)
        (println (str "Image saved successfully to: " output-path)))
      (catch Exception e
        (println (str "Error: " (.getMessage e)))))))

Run the project using:

$ lein run

Generate jar file using lein uberjar, and run it using:

$ java -jar target/uberjar/image_in_resources-0.1.0-SNAPSHOT-standalone.jar

The complete source code can be found here https://gitlab.com/clojure-diary/code/image-in-resources.

Updated: