ani2cape.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. import io
  2. import logging
  3. import time
  4. import uuid
  5. from PIL import Image
  6. logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s', level=logging.INFO)
  7. def scaleImage(img, scale):
  8. if img is None:
  9. return
  10. return img.resize((img.width * scale, img.height * scale))
  11. def readCUR(f, width=-1.0, height=-1.0):
  12. frameImage = Image.open(f, formats=['cur', 'ico']).convert('RGBA')
  13. if (width, height) == (-1.0, -1.0):
  14. return frameImage, (float(frameImage.width), float(frameImage.height))
  15. if -1 in (width, height):
  16. width = height / frameImage.height * frameImage.width if width == -1 else width
  17. height = width / frameImage.width * frameImage.height if height == -1 else height
  18. return frameImage.resize((int(width), int(height))), (width, height)
  19. def analyzeANI(f):
  20. if f.read(4) != b'RIFF':
  21. return {'code': -1, 'msg': 'File is not a ANI File!'}
  22. logging.debug('文件头检查完成!')
  23. fileSize = int.from_bytes(f.read(4), byteorder='little', signed=False)
  24. # if os.path.getsize(filePath) != fileSize:
  25. # return {'code':-2,'msg':'File is damaged!'}
  26. logging.debug('文件长度检查完成!')
  27. if f.read(4) != b'ACON':
  28. return {'code': -1, 'msg': 'File is not a ANI File!'}
  29. logging.debug('魔数检查完成!')
  30. frameRate = (1/60)*1000
  31. while (True):
  32. chunkName = f.read(4)
  33. if chunkName == b'LIST':
  34. break
  35. chunkSize = int.from_bytes(f.read(4), byteorder='little', signed=False)
  36. if chunkName.lower() == b'rate':
  37. logging.debug('发现自定义速率!')
  38. frameRate = frameRate * int.from_bytes(f.read(4), byteorder='little', signed=False)
  39. logging.warning('发现自定义速率!由于GIF限制,将取第一帧与第二帧的速率作为整体速率!')
  40. f.read(chunkSize - 4)
  41. else:
  42. logging.debug('发现自定义Chunk!')
  43. f.read(chunkSize)
  44. listChunkSize = int.from_bytes(f.read(4), byteorder='little', signed=False)
  45. if f.read(4) != b'fram':
  46. return {'code': -3, 'msg': 'File not a ANI File!(No Frames)'}
  47. logging.debug('frame头检查完成!')
  48. frameList = []
  49. nowSize = 4
  50. while (nowSize < listChunkSize):
  51. if f.read(4) != b'icon':
  52. return {'code': -4, 'msg': 'File not a ANI File!(Other Kind Frames)'}
  53. nowSize += 4
  54. subChunkSize = int.from_bytes(f.read(4), byteorder='little', signed=False)
  55. nowSize += 4
  56. frameList.append(f.read(subChunkSize))
  57. nowSize += subChunkSize
  58. return {'code': 0, 'msg': frameList, 'frameRate': frameRate}
  59. def main():
  60. from config import capeConfig
  61. uniqueId = (f'local.{capeConfig['Author'] or 'unknown'}'
  62. f'.{capeConfig['CapeName'] or 'untitled'}'
  63. f'.{time.time()}.{str(uuid.uuid4()).upper()}')
  64. capeData = {
  65. 'Author': capeConfig['Author'],
  66. 'CapeName': capeConfig['CapeName'],
  67. 'CapeVersion': capeConfig['CapeVersion'],
  68. 'Cloud': False,
  69. 'Cursors': {},
  70. 'HiDPI': capeConfig['HiDPI'],
  71. 'Identifier': capeConfig['Identifier'] or uniqueId,
  72. 'MinimumVersion': 2.0,
  73. 'Version': 2.0
  74. }
  75. for cursorType, cursorConfig in capeConfig['Cursors'].items():
  76. cursorSetting = {
  77. 'FrameCount': 1,
  78. 'FrameDuration': cursorConfig['FrameDuration'],
  79. 'HotSpotX': cursorConfig['HotSpot'][0] + 2.0,
  80. 'HotSpotY': cursorConfig['HotSpot'][1] + 2.0,
  81. 'Representations': []
  82. }
  83. hidpiRatio = 2 if capeConfig['HiDPI'] else 1
  84. width, height = cursorConfig.get('Size', (-1.0, -1.0))
  85. with open(cursorConfig['Path'], 'rb') as f:
  86. spriteSheet = None
  87. if (res := analyzeANI(f))['code'] == 0:
  88. logging.info('ANI文件分析完成,帧提取完成!')
  89. cursorSetting['FrameCount'] = len(res['msg'])
  90. for frameIndex in range(len(res['msg'])):
  91. b = io.BytesIO(res['msg'][frameIndex])
  92. frame, (width, height) = readCUR(b, width, height)
  93. position = (2, 2 + int((height + 4) * frameIndex))
  94. if frameIndex == 0:
  95. spriteSheet = Image.new('RGBA', (int(width + 4), int(height + 4) * len(res['msg'])))
  96. spriteSheet.paste(frame, position)
  97. else:
  98. logging.info('尝试作为CUR读入')
  99. frame, (width, height) = readCUR(f, width, height)
  100. spriteSheet = Image.new('RGBA', (int(width + 4), int(height + 4)))
  101. spriteSheet.paste(frame, (2, 2))
  102. logging.info(f'目标尺寸:{width}x{height}@{hidpiRatio}x')
  103. cursorSetting['PointsHigh'], cursorSetting['PointsWide'] = width + 4, height + 4
  104. for scale in (1, 2) if capeConfig['HiDPI'] else (1,):
  105. byteBuffer = io.BytesIO()
  106. scaleImage(spriteSheet, scale).save(byteBuffer, format='tiff', compression='tiff_lzw')
  107. cursorSetting['Representations'].append(byteBuffer.getvalue())
  108. capeData['Cursors'][cursorType] = cursorSetting
  109. from plistlib import dump, FMT_XML
  110. with open(f'{capeData['Identifier']}.cape', 'wb') as f:
  111. dump(capeData, f, fmt=FMT_XML, sort_keys=True, skipkeys=False)
  112. if __name__ == '__main__':
  113. main()