-
Notifications
You must be signed in to change notification settings - Fork 0
/
inplace_green2transp
executable file
·271 lines (179 loc) · 8.12 KB
/
inplace_green2transp
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#!/usr/bin/env python2.6
import cStringIO, datetime, os, glob, re, subprocess, sys
from optparse import OptionParser
from alppng import *
CONVERT = 'convert'
PNGNQ = 'pngnq'
PNGCRUSH = 'pngcrush'
CONVERT_CMD_TMPL = CONVERT + " {in_filename} -alpha set -fuzz 5% -transparent '#00FF00' {out_filename}"
ALPPNG_TOLERANCE = 5
def convert( in_filename ):
out_filename = in_filename
subprocess.check_call( CONVERT_CMD_TMPL.format( **vars()), shell=True ) # Overwrite
def pngnq( in_filename ):
h,t = os.path.splitext( in_filename )
nq = h + '-nq8' + t
subprocess.check_call( ' '.join( [ PNGNQ, in_filename ] ), shell=True )
os.rename( nq, in_filename ) # Overwrite
def pngcrush( in_filename ):
h,t = os.path.splitext( in_filename )
crush = h + '-crush' + t
subprocess.check_call( ' '.join( [ PNGCRUSH, in_filename, crush ] ), shell=True )
os.rename( crush, in_filename ) # Overwrite
def remove_if_plte_trns_fully_transparent( filename, png, n_removed = 0, vspur = False, verbosity = 0, i = 0, n = 0, eta_str = '' ):
'''Input: png object or filename string
Output: pair tuple: (removed, n_removed)
'''
png = alppng.Png( filename ) if png == None else png
# Action 2: check whether the result is fully transparent
removed = False
if alppng.Png_has_plte_trns_and_is_fully_transparent( png ):
# Yes: remove the file
os.remove( filename )
removed = True
if vspur:
s = '{i}/{n}{eta_str}: removed fully transparent file "{filename}"'.format( **vars() ) + (' ' * 10)
if verbosity > 1:
print s
else:
print s + '\r',
return removed,( n_removed + (1 if removed else 0))
def print_usage_and_exit(out = sys.stdout, code = 0):
print >> out
print >> out, __doc__
sys.exit(code)
def ETA( start_datetime, ncomptotal, count ):
delta_t = datetime.datetime.now() - start_datetime
delta_t_sec = delta_t.days * 86400 + delta_t.seconds + delta_t.microseconds * 1e-6
remaining_sec = delta_t_sec * 1.0 / count * ( ncomptotal - count )
remaining = datetime.timedelta( 0, remaining_sec )
return datetime.datetime.now() + remaining
def main( argv, png_rx_str = r'\.[pP][nN][gG]$', pure_green = (0, 255, 0) ):
parser = OptionParser(usage="""usage: %prog [options] file|directory
Examples:
inplace_green2transp.py <dir>
inplace_green2transp.py -v <dir>
inplace_green2transp.py -q <dir>
inplace_green2transp.py -f <filename>
This program modifies all PNGs contained in <dir> and in its
sub-directories. -v and -q are just verbosity/quiet options.
Two actions:
1. Transform: pure green (tolerance 5%) => transparent
2. After 1., delete fully transparent tiles.
ATTENTION: files are directly modified. No safety copy, no undo.
TRAC ticket #7524
""")
parser.add_option("-q", "--quiet",
action="store_true", dest="quiet", default=False,
help='''don't print any status messages to stdout except errors.''')
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help='''print more status messages to stdout.''')
parser.add_option("-f", "--file",
action="store_true", dest="file", default=False,
help='''the parameter is a file, not a directory.''')
(options, args) = parser.parse_args()
argc = len( args )
if argc == 0:
parser.print_help()
sys.exit(1)
verbosity = 1 # standard verbosity (not too much so that performance remains good)
filenamelist = None
rw_dir = args[ 0 ]
if options.verbose:
verbosity = 2 # full verbosity (one print for each file)
elif options.quiet:
verbosity = 0 # no verbosity at all
if options.file:
filenamelist = [ args[ 0 ], ]
#
png_rx = re.compile( png_rx_str )
# Read the list of png files
if not filenamelist:
filenamelist = []
for root, dirs, files in os.walk( rw_dir ):
for name in files:
if None == png_rx.search( name ):
continue
filenamelist.append( os.path.join( root, name ) )
#
n = len( filenamelist )
if verbosity > 0:
print
print 'Found {n} PNG files in: {rw_dir}'.format( **vars() )
print
# Process the files
start_datetime = datetime.datetime.now()
eta_str = ''
n_removed = 0 # Counter for action 2
i = 0
while i < n:
filename = filenamelist[ i ]
i += 1
if not (i % 100):
eta_datetime = ETA( start_datetime, n, i )
eta_str = ' (ETA: {0})'.format( eta_datetime.strftime( '%d.%m.%Y %H:%M:%S' ))
vspur = (verbosity > 1) or ((verbosity > 0) and (not (i % 100)))
#
png = alppng.Png( filename )
if not alppng.Png_has_plte_chunk( png ):
# Fallback: try image magick (mainly for tiles at the border)
# Inconvenient: slower than just modifying the palette
convert( filename )
pngnq( filename )
# pngcrush( filename )
# print 'xxx slow-modified {filename}'.format( **vars() )
if vspur:
s = '{i}/{n}{eta_str}: modified file (using Image Magick, PNGNQ & PNGCRUSH): "{filename}"'.format( **vars() ) + (' ' * 10)
if verbosity > 1:
print s
else:
print s + '\r',
removed, n_removed = remove_if_plte_trns_fully_transparent( filename, None, n_removed = n_removed, vspur = vspur, verbosity = verbosity, i = i, n = n, eta_str = eta_str )
continue
if not alppng.Png_plte_has( png, pure_green, tolerance = ALPPNG_TOLERANCE ): # Should be fast
removed, n_removed = remove_if_plte_trns_fully_transparent( filename, png, n_removed = n_removed, vspur = vspur, verbosity = verbosity, i = i, n = n, eta_str = eta_str )
if removed:
continue
if vspur:
s = '{i}/{n}{eta_str}: skipped file (palette does not have {pure_green}, and file is not fully transparent): "{filename}"'.format( **vars() ) + (' ' * 10)
if verbosity > 1:
print s
else:
print s + '\r',
continue
# Read the PNG file (1 disk access)
csio = cStringIO.StringIO()
csio.write( open( filename, 'rb' ).read() )
# Do the two operations in memory (no disk access)
png = alppng.Png( csio )
modified = alppng.Png_set_replace_plte_colour( png, pure_green, (255,255,255), tolerance = ALPPNG_TOLERANCE )
alppng.Png_set_make_sure_plte_trns( png, modified, 0 )
# Is the resulting PNG fully transparent ?
removed, n_removed = remove_if_plte_trns_fully_transparent( filename, png, n_removed = n_removed, vspur = vspur, verbosity = verbosity, i = i, n = n, eta_str = eta_str )
if removed:
# Yes: remove it (Action 2., 1 disk access)
continue
# No: Write out the result (1 disk access)
open( filename, 'wb' ).write( csio.getvalue() )
if vspur:
s = '{i}/{n}{eta_str}: modified file "{filename}"'.format( **vars() ) + (' ' * 10)
if verbosity > 1:
print s
else:
print s + '\r',
end_datetime = datetime.datetime.now()
delta_t = end_datetime - start_datetime
delta_t_sec = delta_t.days * 86400 + delta_t.seconds + delta_t.microseconds * 1e-6
if verbosity > 0:
print
print
print 'Done.'
if n > 0:
print 'Processed {n} tiles in {delta_t_sec:.2f} second(s)'.format( **vars() )
print 'Speed was: {0:.5} tile(s)/second.'.format( n / delta_t_sec )
print 'Removed {n_removed} fully transparent tiles'.format( **vars() )
print ''
if __name__ == '__main__':
main( sys.argv )