-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgif_to_png.rb
102 lines (73 loc) · 2.67 KB
/
gif_to_png.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
require 'platform'
require 'find'
require 'colored'
require 'win32console' if PLATFORM_IS_WINDOWS
base_dir = ARGV[0]
puts "Finding png files in #{base_dir}"
def is_animated(path)
file = File.open(path, 'rb')
data = file.readlines.join
count = 0
str_loc = 0
while count < 2
graphic_control_block = data.index(/\x00\x21\xF9\x04/, str_loc)
if graphic_control_block
str_loc += 1
#image block should be right after the graphic control block
image_block = data.index(/\x00\x2C/, str_loc)
if image_block && graphic_control_block + 8 == image_block
count += 1
else
break
end
else
break
end
end
file.close
count > 1
end
ordered = true
messages = []
compression_comparator = ->(a,b){
b[:bytes_saved] <=> a[:bytes_saved]
}
if File.exists?(base_dir) && File.directory?(base_dir)
Find.find(base_dir) do |path|
if path =~ /\A([\-\.\:\w\s\b\/\\]+(\/|\\){1})([\-\.\w\b]+)\.gif\z/
relative_path = path.slice(base_dir.length..-1)
if is_animated(path)
#puts "Can't convert #{relative_path}. Is animated".red
else
gif_size = FileTest.size(path)
system("echo #{path} >> #{base_dir}/unanimated_gifs.txt")
png_path = "#{$1}#{$3}.png"
png_tmp_path = "#{$1}#{$3}.png-new"
system("convert.exe \"#{path}\" \"#{png_path}\"")
system("pngcrush -rem alla -reduce -brute -e .png-new \"#{png_path}\" >NUL")
File.delete(png_path)
File.rename(png_tmp_path, png_path)
png_size = FileTest.size(png_path)
if png_size < gif_size
compression_percentage = (1 - (png_size / gif_size.to_f)) * 100.0
compression_percentage_string = "%.2f".green % compression_percentage
if ordered
message = "Converting #{relative_path.yellow}. "
message += "It should change to png ( png size: #{png_size.to_s.green}, gif size: #{gif_size.to_s.red}, %compression: #{compression_percentage_string}"
messages.push({message: message, compression: compression_percentage, bytes_saved: (gif_size - png_size)})
else
print "Converting #{relative_path.yellow}. "
puts "It should change to png ( png size: #{png_size.to_s.green}, gif size: #{gif_size.to_s.red}, %compression: #{compression_percentage_string}"
end
else
#puts "Converting #{relative_path}. Deleting png because it's bigger".yellow
File.delete(png_path)
end
end
end
end
sorted_messages = messages.sort( & compression_comparator)
sorted_messages.each { |message| puts message[:message]}
else
puts "Path not found or it isn't a directory"
end