icon_utils.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from PIL.Image import Resampling
  2. import xml.etree.ElementTree as ET
  3. from PIL import Image
  4. import os
  5. from print_log import printlog
  6. def change_icon_size(image_path, drawablePath, width, height):
  7. if os.path.exists(drawablePath):
  8. im = Image.open(image_path)
  9. out = im.resize((int(width), int(height)), Resampling.LANCZOS)
  10. out.save(drawablePath, im.format)
  11. printlog('[drawablePath] : %s \n replace completed!' % drawablePath)
  12. pass
  13. def replace_icon(temp_dir, icon_path):
  14. am_path = os.path.join(temp_dir, 'AndroidManifest.xml')
  15. allIconSize = {'drawable': '512', 'drawable-ldpi': '72', 'drawable-mdpi': '96', 'drawable-hdpi': '192',
  16. 'drawable-xhdpi': '256'
  17. , 'drawable-xxhdpi': '384', 'drawable-xxxhdpi': '512','drawable-ldpi-v4':'36','drawable-hdpi-v4': '72',
  18. 'drawable-xhdpi-v4': '256', 'drawable-xxhdpi-v4': '384', 'drawable-xxxhdpi-v4': '512',
  19. 'mipmap-ldpi': '36', 'mipmap-mdpi': '96', 'mipmap-hdpi': '192', 'mipmap-xhdpi': '256',
  20. 'mipmap-xxhdpi': '384', 'mipmap-xxxhdpi': '512'
  21. }
  22. roundIconSize = {'mipmap-ldpi': '36', 'mipmap-mdpi': '96', 'mipmap-hdpi': '192', 'mipmap-xhdpi': '256',
  23. 'mipmap-xxhdpi': '384', 'mipmap-xxhdpi-v4': '384', 'mipmap-xxxhdpi': '512'}
  24. ret, icon_name = get_icon_name(am_path)
  25. for iconDir, iconSize in allIconSize.items():
  26. drawablePath = os.path.join(temp_dir, 'res', iconDir, "%s.png" % icon_name)
  27. change_icon_size(icon_path, drawablePath, iconSize, iconSize)
  28. for iconDir, iconSize in roundIconSize.items():
  29. drawablePath = os.path.join(temp_dir, 'res', iconDir, "%s_round.png" % icon_name)
  30. change_icon_size(icon_path, drawablePath, iconSize, iconSize)
  31. def get_icon_name(am_path):
  32. if not os.path.exists(am_path):
  33. return False, "AndroidManifest.xml is not exists!"
  34. namespace = "http://schemas.android.com/apk/res/android"
  35. amTree = ET.parse(am_path)
  36. amRoot = amTree.getroot()
  37. applicationNode = amRoot.find("application")
  38. iconName = applicationNode.attrib.get("{%s}icon" % namespace)
  39. if iconName is None:
  40. return False, "cant find icon name"
  41. iconName = iconName.split("/")[1]
  42. return True, iconName
  43. pass