Guest User

Untitled

a guest
Oct 22nd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. import win32api, win32con
  2. import os, os.path
  3. import struct
  4. import math
  5.  
  6. def checkPath(path, mode):
  7. if not os.path.exists(path) or not os.path.isfile(path):
  8. raise ValueError("{0} does not exist or isn't a file.".format(path))
  9. if not os.access(path, mode):
  10. raise ValueError("Insufficient permissions: {0}".format(path))
  11.  
  12. def updateExecutableIcon(executablePath, iconPath):
  13. """
  14. Updates the icon of a Windows executable file.
  15. """
  16.  
  17. checkPath(executablePath, os.W_OK)
  18. checkPath(iconPath, os.R_OK)
  19.  
  20. handle = win32api.BeginUpdateResource(executablePath, False)
  21.  
  22. icon = open(iconPath, "rb")
  23.  
  24. fileheader = icon.read(6)
  25.  
  26. # Read icon data
  27. image_type, image_count = struct.unpack("xxHH", fileheader)
  28. print "Icon file has type {0} and contains {1} images.".format(image_type, image_count)
  29.  
  30. icon_group_desc = struct.pack("<HHH", 0, image_type, image_count)
  31. icon_sizes = []
  32. icon_offsets = []
  33.  
  34. # Read data of all included icons
  35. for i in range(1, image_count + 1):
  36. imageheader = icon.read(16)
  37. width, height, colors, panes, bits_per_pixel, image_size, offset =\
  38. struct.unpack("BBBxHHLL", imageheader)
  39. print "Image is {0}x{1}, has {2} colors in the palette, {3} planes, {4} bits per pixel.".format(
  40. width, height, colors, panes, bits_per_pixel);
  41. print "Image size is {0}, the image content has an offset of {1}".format(image_size, offset);
  42.  
  43. icon_group_desc = icon_group_desc + struct.pack("<BBBBHHIH",
  44. width, # Icon width
  45. height, # Icon height
  46. colors, # Colors (0 for 256 colors)
  47. 0, # Reserved2 (must be 0)
  48. panes, # Color planes
  49. bits_per_pixel, # Bits per pixel
  50. image_size, # ImageSize
  51. i # Resource ID
  52. )
  53. icon_sizes.append(image_size)
  54. icon_offsets.append(offset)
  55.  
  56. # Read icon content and write it to executable file
  57. for i in range(1, image_count + 1):
  58. icon_content = icon.read(icon_sizes[i - 1])
  59. print "Read {0} bytes for image #{1}".format(len(icon_content), i)
  60. win32api.UpdateResource(handle, win32con.RT_ICON, i, icon_content)
  61.  
  62. win32api.UpdateResource(handle, win32con.RT_GROUP_ICON, "MAINICON", icon_group_desc)
  63.  
  64. win32api.EndUpdateResource(handle, False)
  65.  
  66. # Use some files I found lying around
  67. updateExecutableIcon("example.exe", "test.ico")
Add Comment
Please, Sign In to add comment