Skip to content

Commit cf85f2f

Browse files
author
BoboTiG
committed
save_img(): little optimisation
1 parent 07a88a1 commit cf85f2f

1 file changed

Lines changed: 11 additions & 14 deletions

File tree

mss.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,8 @@
2929

3030
from struct import pack
3131
from platform import system
32-
import os.path
32+
from zlib import compress, crc32
3333
import sys
34-
import zlib
3534

3635

3736
class ScreenshotError(Exception):
@@ -216,39 +215,37 @@ def save_img(self, data, width, height, output):
216215
http://inaps.org/journal/comment-fonctionne-le-png
217216
'''
218217

219-
self.debug('save_img')
220-
221-
to_take = (width * 3 + 3) & -4
222-
padding = 0 if to_take % 8 == 0 else (to_take % 8) // 2
218+
zcrc32 = crc32
219+
zcompr = compress
220+
len_sl = width * 3
223221
scanlines = b''.join(
224-
[b'0' + data[(y * to_take):(y * to_take) + to_take - padding]
222+
[b'0' + data[y * len_sl:y * len_sl + len_sl]
225223
for y in range(height)])
226224

227225
magic = pack(b'>8B', 137, 80, 78, 71, 13, 10, 26, 10)
228226

229227
# Header: size, marker, data, CRC32
230228
ihdr = [b'', b'IHDR', b'', b'']
231229
ihdr[2] = pack(b'>2I5B', width, height, 8, 2, 0, 0, 0)
232-
ihdr[3] = pack(b'>I', zlib.crc32(b''.join(ihdr[1:3])) & 0xffffffff)
230+
ihdr[3] = pack(b'>I', zcrc32(b''.join(ihdr[1:3])) & 0xffffffff)
233231
ihdr[0] = pack(b'>I', len(ihdr[2]))
234232

235233
# Data: size, marker, data, CRC32
236234
idat = [b'', b'IDAT', b'', b'']
237-
idat[2] = zlib.compress(scanlines, 9)
238-
idat[3] = pack(b'>I', zlib.crc32(b''.join(idat[1:3])) & 0xffffffff)
235+
idat[2] = zcompr(scanlines, 9)
236+
idat[3] = pack(b'>I', zcrc32(b''.join(idat[1:3])) & 0xffffffff)
239237
idat[0] = pack(b'>I', len(idat[2]))
240238

241239
# Footer: size, marker, None, CRC32
242240
iend = [b'', b'IEND', b'', b'']
243-
iend[3] = pack(b'>I', zlib.crc32(iend[1]) & 0xffffffff)
241+
iend[3] = pack(b'>I', zcrc32(iend[1]) & 0xffffffff)
244242
iend[0] = pack(b'>I', len(iend[2]))
245243

246244
with open(output, 'wb') as fileh:
247245
fileh.write(
248246
magic + b''.join(ihdr) + b''.join(idat) + b''.join(iend))
249-
if not os.path.isfile(output):
250-
msg = 'Impossible to write data to file "{}".'.format(output)
251-
raise ScreenshotError(msg)
247+
return
248+
raise ScreenshotError('MSS: error writing data to "{}".'.format(output))
252249

253250

254251
class MSSMac(MSS):

0 commit comments

Comments
 (0)