Permalink
Browse files

Project creation

  • Loading branch information...
0 parents commit 6cadbacbf41a6d1b9e0e581f13347c4684332adf @LauJensen committed Feb 12, 2010
Showing with 72 additions and 0 deletions.
  1. +7 −0 README
  2. +10 −0 project.clj
  3. +55 −0 src/claskii.clj
7 README
@@ -0,0 +1,7 @@
+The code used for this blogpost:
+
+http://www.bestinclass.dk/index.php/2010/02/my-tribute-to-steve-ballmer/
+
+-------------------------
+
+A small Clojure program which converts images to ascii-art, either by outputting html or println directly in the REPL.
@@ -0,0 +1,10 @@
+(defproject cloneit "1.0.0"
+ :description "Image to Ascii-art converter"
+ :url "http://www.bestinclass.dk"
+ :library-path "lib/"
+ :namespaces [claskii]
+ :main claskii
+ :dependencies [[org.clojure/clojure "1.1.0-new-SNAPSHOT"]
+ [org.clojure/clojure-contrib "1.1.0-new-SNAPSHOT"]
+ [compojure "0.3.2"]]
+ :dev-dependencies [[swank-clojure "1.1.0"]])
@@ -0,0 +1,55 @@
+(ns claskii
+ (:import (java.awt Color RenderingHints)
+ (java.awt.image BufferedImage)
+ (javax.swing ImageIcon)
+ (javax.imageio ImageIO)
+ (java.io File))
+ (:use compojure
+ (clojure.contrib duck-streams seq-utils)))
+
+(def ascii-chars [\# \A \@ \% \$ \+ \= \* \: \, \. \space])
+
+(defmacro get-properties [obj & properties]
+ (let [target (gensym)]
+ `(let [~target ~obj]
+ (vector ~@(for [property properties]
+ `(~property ~target))))))
+
+(defn scale-image [uri new-width]
+ (let [image (-> (ImageIcon. uri) .getImage)
+ new-height (* (/ new-width (.getWidth image)) (.getHeight image))
+ scaled-image (BufferedImage. new-width new-height
+ BufferedImage/TYPE_INT_RGB)
+ gfx2d (doto (.createGraphics scaled-image)
+ (.setRenderingHint RenderingHints/KEY_INTERPOLATION
+ RenderingHints/VALUE_INTERPOLATION_BILINEAR)
+ (.drawImage image 0 0 new-width new-height nil)
+ .dispose)]
+ scaled-image))
+
+(defn ascii [img x y color?]
+ (let [[red green blue] (get-properties ( Color. (.getRGB img x y))
+ .getRed .getGreen .getBlue)
+ peak (apply max [red green blue])
+ idx (if (zero? peak)
+ (dec (count ascii-chars))
+ (dec (int (+ 1/2 (* (count ascii-chars) (/ peak 255))))))
+ output (nth ascii-chars (if (pos? idx) idx 0)) ]
+ (if color?
+ (html [:span {:style (format "color: rgb(%s,%s,%s);" red green blue)} output])
+ output)))
+
+(defn convert-image [uri w color?]
+ (let [raw-image (scale-image uri w)
+ ascii-image (->> (for [y (range (.getHeight raw-image))
+ x (range (.getWidth raw-image))]
+ (ascii raw-image x y color?))
+ (partition w))
+ output (->> ascii-image
+ (interpose (if color? "<BR/>" \newline))
+ flatten)]
+ (if color?
+ (html [:pre {:style "font-size:5pt; letter-spacing:1px;
+ line-height:4pt; font-weight:bold;"}
+ output])
+ (println output))))

0 comments on commit 6cadbac

Please sign in to comment.