Skip to content

Instantly share code, notes, and snippets.

@cxx
Created May 23, 2011 11:27
Show Gist options
  • Save cxx/986565 to your computer and use it in GitHub Desktop.
Save cxx/986565 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'open-uri'
require 'net/http'
require 'securerandom'
require 'tempfile'
require 'RMagick'
def bin(str)
str.dup.force_encoding("ASCII-8BIT")
end
include Magick
COLS = 18
ChannelDepths = [5, 5, 4]
files = []
comment = nil
ARGV.each do |s|
if File.exist?(s)
files << s
else
comment = s.encode("UTF-8")
end
end
if files.empty?
temp = Tempfile.new(["kanji", ".png"])
files << temp.path
temp.close
system("screencapture -i #{files.first}")
end
files.each do |file|
blob = open(file, "rb:ASCII-8BIT").read
image = Image::from_blob(blob).first.resize_to_fill(COLS)
[RedChannel, GreenChannel, BlueChannel].zip(ChannelDepths).each {|a| image.set_channel_depth(*a) }
image = image.quantize(13, RGBColorspace, NoDitherMethod)
pixels = image.get_pixels(0, 0, COLS, COLS)
palette = pixels.uniq
palette_nums = palette.map do |pixel|
[:red, :green, :blue].zip(ChannelDepths).inject(0) do |result, a|
(result << a[1]) | (pixel.send(a[0]) >> (QuantumDepth - a[1]))
end
end
pixel_nums = pixels.each_slice(3).map {|a| a.inject(0) {|result, p| (result << 4) | palette.index(p) }}
if comment
comment.unpack("U*").first(2 * COLS/3 * COLS / 16).map do |c|
14.step(0, -2).map {|i| (c >> i) & 0x03 }
end.flatten.each_with_index {|n, i| pixel_nums[i] |= n << 12 }
end
kanji = (palette_nums + pixel_nums).map {|n| n + 0x4e00 }.pack("U*")
filename = bin(File.basename(file))
begin
boundary = SecureRandom.base64
end while [blob, filename].any? {|v| v.include?(boundary) }
data = "--#{boundary}\r\n" + [[{ "name" => "file", "filename" => filename }, blob], [{ "name" => "key" }, bin(kanji)]].map do |a|
names = a[0].map {|k, v| %!#{k}="#{v}"! } * "; "
"Content-Disposition: form-data; #{names}\r\n\r\n#{a[1]}\r\n--#{boundary}"
end * "\r\n" + "--"
Net::HTTP.start("k-host.appspot.com") do |http|
http.post("/", data, "Content-Type" => "multipart/form-data; boundary=#{boundary}")
end
uri = "k-host.appspot.com/#{kanji}"
puts uri
system("echo -n #{uri} | pbcopy")
system("open https://twitter.com/?status=#{uri}")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment