Skip to content

Instantly share code, notes, and snippets.

@timknip
Created October 5, 2016 17:21
Show Gist options
  • Save timknip/4fb6712a19236db194c6ceaf959a637b to your computer and use it in GitHub Desktop.
Save timknip/4fb6712a19236db194c6ceaf959a637b to your computer and use it in GitHub Desktop.
transient crop
(defn crop-old
[ctx w h]
(let [data (.-data (.getImageData ctx 0 0 w h))
s (* w h 4)
[a b] (loop [y 0 px [] py []]
(if (< y h)
(let [[x' y']
(loop [x 0 px' px py' py]
(if (< x w)
(let [a? (> (aget data (+ (* (+ (* y w) x) 4) 3)) 0)]
(recur (inc x) (if a? (conj px' x) px') (if a? (conj py' y) py')))
[px' py']))]
(recur (inc y) x' y'))
[px py]))
px (sort a)
py (sort b)
n (- (count px) 1)
w' (- (last px) (first px))
h' (- (last py) (first py))
cut (.getImageData ctx (first px) (first py) w' h')
c (create-canvas w' h')
cx (.getContext c "2d")]
(.putImageData cx cut 0 0)
(.toBuffer c)))
(defn crop
[ctx w h]
(let [data (.-data (.getImageData ctx 0 0 w h))
s (* w h 4)
[a b] (loop [y 0 px (transient []) py (transient [])]
(if (< y h)
(let [[x' y']
(loop [x 0 px' px py' py]
(if (< x w)
(let [a? (> (aget data (+ (* (+ (* y w) x) 4) 3)) 0)]
(recur (inc x) (if a? (conj! px' x) px') (if a? (conj! py' y) py')))
[px' py']))]
(recur (inc y) x' y'))
[(persistent! px) (persistent! py)]))
px (sort a)
py (sort b)
n (- (count px) 1)
w' (- (last px) (first px))
h' (- (last py) (first py))
cut (.getImageData ctx (first px) (first py) w' h')
c (create-canvas w' h')
cx (.getContext c "2d")]
(.putImageData cx cut 0 0)
(.toBuffer c)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment