forked from onefrankguy/rogue-reversal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rle.rb
executable file
·57 lines (44 loc) · 927 Bytes
/
rle.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env ruby
require 'chunky_png'
require 'json'
file = ARGV[0]
image = ChunkyPNG::Image.from_file(file)
height = image.dimension.height
width = image.dimension.width
character = 97
histogram = {}
rle = ''
last = nil
count = 0
total = 0
(0...height).each do |y|
(0...width).each do |x|
color = image[x,y]
unless histogram.has_key? color
histogram[color] = character.chr
character += 1
end
last = color if last.nil?
if last != color
rle << "#{count}#{histogram[last]}"
total += count
last = color
count = 0
end
count += 1
end
end
rle << "#{count}#{histogram[last]}"
total += count
abort 'Missing data!' if total != width * height
histogram = histogram.invert
histogram.each do |key, color|
histogram[key] = ChunkyPNG::Color.to_hex(color)
end
json = {
width: width,
height: height,
data: rle,
values: histogram
}
puts json.to_json