33Source: https://github.com/BoboTiG/python-mss
44"""
55
6+ import os
67import struct
78import zlib
89from typing import TYPE_CHECKING
@@ -22,31 +23,35 @@ def to_png(data, size, level=6, output=None):
2223 :param int level: PNG compression level.
2324 :param str output: Output file name.
2425 """
26+ # pylint: disable=too-many-locals
27+
28+ pack = struct .pack
29+ crc32 = zlib .crc32
2530
2631 width , height = size
2732 line = width * 3
28- png_filter = struct . pack (">B" , 0 )
33+ png_filter = pack (">B" , 0 )
2934 scanlines = b"" .join (
3035 [png_filter + data [y * line : y * line + line ] for y in range (height )]
3136 )
3237
33- magic = struct . pack (">8B" , 137 , 80 , 78 , 71 , 13 , 10 , 26 , 10 )
38+ magic = pack (">8B" , 137 , 80 , 78 , 71 , 13 , 10 , 26 , 10 )
3439
3540 # Header: size, marker, data, CRC32
3641 ihdr = [b"" , b"IHDR" , b"" , b"" ]
37- ihdr [2 ] = struct . pack (">2I5B" , width , height , 8 , 2 , 0 , 0 , 0 )
38- ihdr [3 ] = struct . pack (">I" , zlib . crc32 (b"" .join (ihdr [1 :3 ])) & 0xFFFFFFFF )
39- ihdr [0 ] = struct . pack (">I" , len (ihdr [2 ]))
42+ ihdr [2 ] = pack (">2I5B" , width , height , 8 , 2 , 0 , 0 , 0 )
43+ ihdr [3 ] = pack (">I" , crc32 (b"" .join (ihdr [1 :3 ])) & 0xFFFFFFFF )
44+ ihdr [0 ] = pack (">I" , len (ihdr [2 ]))
4045
4146 # Data: size, marker, data, CRC32
4247 idat = [b"" , b"IDAT" , zlib .compress (scanlines , level ), b"" ]
43- idat [3 ] = struct . pack (">I" , zlib . crc32 (b"" .join (idat [1 :3 ])) & 0xFFFFFFFF )
44- idat [0 ] = struct . pack (">I" , len (idat [2 ]))
48+ idat [3 ] = pack (">I" , crc32 (b"" .join (idat [1 :3 ])) & 0xFFFFFFFF )
49+ idat [0 ] = pack (">I" , len (idat [2 ]))
4550
4651 # Footer: size, marker, None, CRC32
4752 iend = [b"" , b"IEND" , b"" , b"" ]
48- iend [3 ] = struct . pack (">I" , zlib . crc32 (iend [1 ]) & 0xFFFFFFFF )
49- iend [0 ] = struct . pack (">I" , len (iend [2 ]))
53+ iend [3 ] = pack (">I" , crc32 (iend [1 ]) & 0xFFFFFFFF )
54+ iend [0 ] = pack (">I" , len (iend [2 ]))
5055
5156 if not output :
5257 # Returns raw bytes of the whole PNG data
@@ -58,4 +63,8 @@ def to_png(data, size, level=6, output=None):
5863 fileh .write (b"" .join (idat ))
5964 fileh .write (b"" .join (iend ))
6065
66+ # Force write of file to disk
67+ fileh .flush ()
68+ os .fsync (fileh .fileno ())
69+
6170 return None
0 commit comments