LoginSignup
0

More than 3 years have passed since last update.

posted at

updated at

apng を python で見つける

python でバイナリーを解析する勉強がてらに書いてみました。

crc32 というライブラリが バイナリデータと ASCII データ を変換するのに便利そうだったため、これを使う。

apng.py

from binascii import crc32

with open('anime.png', 'rb') as f:
  if f.read(8) != b'\x89PNG\r\n\x1a\n':
      raise Exception('image is not png')
  f.read(25)
  buf = f.read(4)
  while buf != b'':
      length = int.from_bytes(buf, 'big')
      data = f.read(4 + length)

      if data[:4] == b'acTL':
        num_frames = int.from_bytes(data[4:8], 'big')
        if num_frames > 1:
          print('is apng')
        break

      if data[:4] == b'IDAT':
        break

      f.read(4)
      buf = f.read(4)

ちなみに apng のデータ構造の説明はこちら
https://developer.mozilla.org/ja/docs/Animated_PNG_graphics

と思ったら 、きちんとしたライブラリもあったね汗
https://pypi.org/project/apng/

今度はこっちを使ってみるか!

お粗末さまでした!

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0