forked from tmm1/emoji-extractor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
emoji_extractor.rb
58 lines (48 loc) · 1.31 KB
/
emoji_extractor.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
58
# stolen largely from http://www.ruby-forum.com/topic/140784
require 'stringio'
require 'fileutils'
def extract_chunk(input, output)
lenword = input.read(4)
length = lenword.unpack('N')[0]
type = input.read(4)
data = length>0 ? input.read(length) : ""
crc = input.read(4)
return nil if length<0 || !(('A'..'z')===type[0,1])
#return nil if validate_crc(type+data, crc)
output.write lenword
output.write type
output.write data
output.write crc
return [type, data]
end
def extract_png(input)
buf = StringIO.new
hdr = input.read(8)
raise "Not a PNG File" if hdr[0,4]!= "\211PNG"
raise "file not in binary mode" if hdr[4,4]!="\r\n\032\n"
buf.write(hdr)
height, width = 0, 0
loop do
chunk_type, chunk_data = extract_chunk(input,buf)
height, width = chunk_data.unpack('NN') if chunk_type == 'IHDR'
break if chunk_type.nil? || chunk_type == 'IEND'
end
FileUtils.mkdir_p(dir = "images/#{height}x#{width}")
if @prev != dir
@n = 0
@prev = dir
end
buf.rewind
ofp = File.new("#{dir}/#{@n+=1}.png","wb")
ofp.write buf.read
ofp.close
end
ttf = File.new("/System/Library/Fonts/Apple Color Emoji.ttf","rb")
ttf_data = ttf.read
pos = 0
while m = /\211PNG/.match(ttf_data[pos..-1])
raise "no PNG found" if !m
pos += m.begin(0) + 1
ttf.seek(pos-1)
extract_png(ttf)
end