png_to_ico.py 671 B

123456789101112131415161718192021
  1. import struct, os, sys
  2. def _png_size(data):
  3. # PNG IHDR chunk at offset 16: 4 bytes width, 4 bytes height
  4. return struct.unpack_from('>II', data, 16)
  5. def png_to_ico(png_path, ico_path):
  6. with open(png_path, 'rb') as f:
  7. png_data = f.read()
  8. w, h = _png_size(png_data)
  9. png_data = png_data # full PNG data as icon payload
  10. header = struct.pack('<HHH', 0, 1, 1)
  11. entry = struct.pack('<BBBBHHII',
  12. w if w < 256 else 0,
  13. h if h < 256 else 0,
  14. 0, 0, 1, 32, len(png_data), 22)
  15. with open(ico_path, 'wb') as f:
  16. f.write(header + entry + png_data)
  17. if __name__ == '__main__':
  18. png_to_ico(sys.argv[1], sys.argv[2])