ani2cape.py 5.7 KB

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