icon_utils.py 2.2 KB

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