Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
簡易PNGエンコーダ
#coding:utf-8
#Make a PNG file
IMAGE = (
'0000000000000000',
'0000000000000000',
'0111111111111110',
'0000000000000000',
'0000111111110000',
'0000010000010000',
'0000010000000000',
'0000010000000000',
'0000011111000000',
'0000010000000000',
'0000010000000000',
'0000010000000000',
'0000111100000000',
'0000000000000000',
'0111111111111110',
'0000000000000000',
)
outname = 'test.png'
import struct
import binascii
import zlib
def crcMaker(data):
return binascii.crc32(data)
def chunkMaker(name, chunkData):
CRC = crcMaker(name + chunkData)
body_len = len(chunkData)
chunk = struct.pack('> I 4s {}s I'.format(body_len),
body_len, name, chunkData, CRC)
return chunk
def split_str(s, n):
length = len(s)
return [s[i:i+n] for i in range(0, length, n)]
def hexize(data):
out = list(map(lambda x:int(x,2), split_str(data, 8)))
return out
data = bytes()
#header
data += bytes((0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A))
#IHDR
width = len(IMAGE[0])
height = len(IMAGE)
depth = 1
colourType = 0
compress = 0
filterType = 0
adam7 = False
chunkData = struct.pack('> I I B B B B ?',
width, height, depth, colourType, compress, filterType, adam7)
data += chunkMaker(b'IHDR', chunkData)
#IDAT
filteredImage = bytes()
filterMode = [0x00,]
inputLine = list()
[inputLine.extend(filterMode+hexize(l)) for l in IMAGE]
chunkData = zlib.compress(bytes(inputLine))
data += chunkMaker(b'IDAT', chunkData)
#IEND
data += chunkMaker(b'IEND', b'')
with open(outname, 'wb') as f:
f.write(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.