Skip to content

Instantly share code, notes, and snippets.

@cxx
Last active August 29, 2015 13:59
Show Gist options
  • Save cxx/10843244 to your computer and use it in GitHub Desktop.
Save cxx/10843244 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'open-uri'
require 'RMagick'
include Magick
palette = Hash[ *(
[ ["000000", "\u{2660}" ], ["157569", "\u{1f5fd}"], ["226699", "\u{1f17f}"],
["231f20", "\u{2b1b}" ], ["292f33", "\u{1f3b1}"], ["3b88c3", "\u{2139}" ],
["4288c1", "\u{1f53d}"], ["553986", "\u{1f47e}"], ["55acee", "\u{1f6b9}"],
["58595b", "\u{1f3a5}"], ["5c913b", "\u{264a}" ], ["5dadec", "\u{1f499}"],
["662113", "\u{1f3c8}"], ["66757f", "\u{1f311}"], ["744eaa", "\u{1f346}"],
["77b255", "\u{2705}" ], ["78b159", "\u{1f4b9}"], ["8899a6", "\u{1f4bf}"],
["9266cc", "\u{1f233}"], ["99aab5", "\u{1f4f6}"], ["9a4e1c", "\u{1f4bc}"],
["a6d388", "\u{1f45d}"], ["aa8dd8", "\u{1f45a}"], ["aa8ed6", "\u{1f47f}"],
["bcbec0", "\u{1f480}"], ["bdddf4", "\u{1f4ac}"], ["be1931", "\u{1f17e}"],
["bf6952", "\u{1f4a9}"], ["c1694f", "\u{1f43b}"], ["c6e4b5", "\u{1f4b6}"],
["cbb8e9", "\u{1f4b7}"], ["ccd6dd", "\u{1f315}"], ["d99e82", "\u{270a}" ],
["da2f47", "\u{1f621}"], ["dd2e44", "\u{1f234}"], ["e1e8ed", "\u{2709}" ],
["e6aaaa", "\u{1f43d}"], ["e6e7e8", "\u{2b1c}" ], ["e75a70", "\u{1f496}"],
["ea596e", "\u{1f6ba}"], ["edbb9f", "\u{1f64c}"], ["f18f26", "\u{1f383}"],
["f4900c", "\u{1f237}"], ["f4abba", "\u{1f416}"], ["fcab40", "\u{1f52f}"],
["fdcb58", "\u{1f49b}"], ["fdd888", "\u{1f4b0}"], ["ff886c", "\u{1f351}"],
["ffac33", "\u{1f536}"], ["ffcc4d", "\u{1f61e}"], ["ffd983", "\u{1f4dc}"]
].map do |hcol, char|
col = hcol.scan(/../).map {|h| h.hex * QuantumRange / 0xff }
[Pixel.new(*col, 0), char]
end.flatten) ]
max_chars = 140
max_cols = 17
src = open(ARGV.first, "rb:ASCII-8BIT") {|f| Image::from_blob(f.read).first }
xres, yres = src.x_resolution, src.y_resolution
xres = yres = 1.0 if xres == 0 or yres == 0
ratio = (src.columns/xres) / (src.rows/yres)
if ratio >= max_cols
cols, rows = max_cols, 1
elsif ratio <= 2.0/max_chars
cols, rows = 1, max_chars/2
else
cols = [Math.sqrt(max_chars*ratio).floor, max_cols].min
rows = (cols / ratio).round
while (cols+1)*rows-1 > max_chars
if ratio >= 1
cols -= 1
rows = (cols / ratio).round
else
rows -= 1
cols = (rows * ratio).round
end
end
end
ref = Image.new(palette.size, 1)
ref.store_pixels(0, 0, ref.columns, 1, palette.keys)
img = src.resize(cols, rows).remap(ref, NoDitherMethod)
result = (0...rows).map do |y|
palette.values_at(*img.get_pixels(0, y, cols, 1)).join
end.join("\n")
puts result
begin
require 'launchy'
query = URI.encode_www_form({"text" => result})
Launchy.open("https://twitter.com/share?#{query}")
rescue LoadError
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment