Skip to content

Instantly share code, notes, and snippets.

@timknip
Created October 5, 2016 22:02
Show Gist options
  • Save timknip/13262fba391878591361e4da1b00953d to your computer and use it in GitHub Desktop.
Save timknip/13262fba391878591361e4da1b00953d to your computer and use it in GitHub Desktop.
(defn trimmed-bounds
[ctx w h]
(let [data (.-data (.getImageData ctx 0 0 w h))]
(loop [y 0 minx Infinity miny Infinity maxx -Infinity maxy -Infinity]
(if (< y h)
(let [yw (* y w)
minx' (loop [x 0]
(when (< x w)
(if (= (aget data (+ (* (+ yw x) 4) 3)) 0)
(recur (inc x))
x)))
maxx' (loop [x (- w 1)]
(when (> x -1)
(if (= (aget data (+ (* (+ yw x) 4) 3)) 0)
(recur (dec x))
x)))]
(if (and (nil? minx') (nil? maxx'))
(recur (inc y) minx miny maxx maxy)
(recur (inc y) (min minx minx') (min miny y) (max maxx maxx') (max maxy y))))
[minx miny maxx maxy]))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment