Skip to content

Instantly share code, notes, and snippets.

@cxx
Created May 20, 2011 19:11
Show Gist options
  • Save cxx/983567 to your computer and use it in GitHub Desktop.
Save cxx/983567 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'open-uri'
require 'RMagick'
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
files.each do |file|
image = Image::from_blob(open(file, "rb:ASCII-8BIT").read).first.resize_to_fill(COLS)
[RedChannel, GreenChannel, BlueChannel].zip(ChannelDepths).each {|a| image.set_channel_depth(*a) }
image = image.quantize(16, 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
puts (palette_nums + pixel_nums).map {|n| n + 0x4e00 }.pack("U*")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment