0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python3】.cim と .png の相互変換

Posted at

https://mell0w-5phere.net/jaded5phere/2020/04/22/convert-cim/ の逆版も書いて合わせました。

import zlib
from PIL import Image

formats = {
    3: "RGB",
    4: "RGBA",
}

formats_return = {
    "RGB":3,
    "RGBA":4
}

def cim_to_png(cim_dir, png_dir):
    with open(cim_dir, 'rb') as f:
        b = zlib.decompress(f.read())
    im = Image.frombytes(formats[int.from_bytes(b[8:12], "big")], (int.from_bytes(b[:4], "big"), int.from_bytes(b[4:8], "big"),), b[12:])
    with open(png_dir, "wb") as f:
        im.save(f, format="png")


def png_to_cim(png_dir, cim_dir):
    with open(png_dir, "rb") as f:
        img = Image.open(f)
        b = b''.join([img.width.to_bytes(4, 'big'), img.height.to_bytes(4, 'big'), formats_return[img.mode].to_bytes(4, 'big'), img.tobytes()])
    with open(cim_dir, "wb") as f:
        f.write(zlib.compress(b))

バイナリの統合とかで少し詰まったので備忘録がてら。cimファイルの変換方法とか書いてあるサイトが少なすぎたので同じ目的で困ってる人が減るといいなあと思いました。

0
1
0

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
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?