74 lines
2.7 KiB
Clojure
74 lines
2.7 KiB
Clojure
(ns yenu.helpers.images
|
|
(:require [image-resizer.core :refer :all]
|
|
[image-resizer.util :as utils]
|
|
[image-resizer.format :refer :all]
|
|
[image-resizer.crop :refer :all]
|
|
[clojure.java.io :as io]
|
|
[digest :as digest]
|
|
[me.raynes.fs :as fs]
|
|
[clj-exif-orientation.core :as exif]
|
|
[yenu.config :refer [env]]))
|
|
|
|
;;; HINT: To use the env function, the webserver need to be started with
|
|
;;; (start) in the 'user namespace.
|
|
(defn data-path
|
|
([] (data-path ""))
|
|
([& args]
|
|
(let [postfix (apply io/file args)]
|
|
(.getPath (io/file (env :user-dir) "data" postfix)))))
|
|
|
|
(defn create-needed-folders []
|
|
(if (not (fs/exists? (data-path "to-process")))
|
|
(fs/mkdirs (data-path "to-process")))
|
|
(if (not (fs/exists? (data-path "gallery")))
|
|
(map #(fs/mkdirs (data-path "gallery" %))
|
|
["normal" "raw" "thumbnails"])))
|
|
|
|
(defn target-image-filename [image-file-path]
|
|
(let [file (io/file image-file-path)]
|
|
(str (.lastModified file) "-" (digest/md5 file))))
|
|
|
|
(defn delete-image! [image-hash]
|
|
(run! #(fs/delete (data-path "gallery" % (str image-hash ".png")))
|
|
["normal" "raw" "thumbnails"]))
|
|
|
|
(defn scale-thumbnail [width]
|
|
#(let [image-file %
|
|
[orig-width orig-height] (dimensions (utils/buffered-image image-file))]
|
|
(if (< orig-width orig-height)
|
|
(let [resized-img (resize-to-width image-file width)
|
|
[w h] (dimensions resized-img)
|
|
crop-margin (quot (- h width) 2)]
|
|
(crop-from resized-img 0 crop-margin width width))
|
|
(let [resized-img (resize-to-height image-file width)
|
|
[w h] (dimensions resized-img)
|
|
crop-margin (quot (- w width) 2)]
|
|
(crop-from resized-img crop-margin 0 width width)))))
|
|
|
|
(defn scale-normal [width height]
|
|
#(resize % width height))
|
|
|
|
(defn save [fn params filepath target-filepath]
|
|
(let [file (exif/without-exif (io/file filepath))]
|
|
(as-file ((apply fn params) file)
|
|
target-filepath
|
|
:verbatim)))
|
|
|
|
(defn scale-image-and-save [filepath]
|
|
(let [image-hash (target-image-filename filepath)
|
|
file-extension (fs/extension filepath)
|
|
new-raw-file-name (str image-hash file-extension)
|
|
new-file-name (str image-hash ".png")]
|
|
(fs/copy filepath (data-path "gallery" "raw" new-file-name))
|
|
(save scale-normal [1024 768] filepath (data-path "gallery" "normal" new-file-name))
|
|
(save scale-thumbnail [250] filepath (data-path "gallery" "thumbnails" new-file-name))
|
|
image-hash))
|
|
|
|
(defn process-image [filepath]
|
|
(let [image-hash (scale-image-and-save filepath)]
|
|
(fs/delete filepath)
|
|
image-hash))
|
|
|
|
(defn process-all-images []
|
|
(pmap process-image (fs/list-dir (data-path "to-process"))))
|