Skip to content

Instantly share code, notes, and snippets.

@masui masui/png.coffee
Created Jul 13, 2014

Embed
What would you like to do?
自力でPNGを作成する
#
# PNGを自力で生成する (masui 2014/07/13 14:26:29)
#
# こういう感じのRGB配列をPNGにする
# data = [
# [[0, 0, 0], [100, 100, 100], [200, 200, 200]],
# [[0, 0, 0], [100, 100, 100], [200, 200, 200]],
# [[0, 0, 0], [100, 100, 100], [200, 200, 200]]
# ]
#
crc = require 'crc'
zlib = require 'zlib'
class PNG
chunk = (type, data) ->
buf = new Buffer data.length+12
buf.writeInt32BE data.length, 0
buf.write type, 4
data.copy buf, 8
buf.writeUInt32BE parseInt(crc.crc32(type+data),16), data.length+8
buf
png: (data, callback, depth=8, color_type=2) ->
height = data.length
width = data[0].length
buf1 = new Buffer "\x89PNG\r\n\x1a\n", 'ascii'
buf = new Buffer 13, 'ascii'
buf.writeUInt32BE width, 0
buf.writeUInt32BE height, 4
buf.writeUInt8 depth, 8
buf.writeUInt8 color_type, 9
buf.writeUInt8 0, 10
buf.writeUInt8 0, 11
buf.writeUInt8 0, 12
buf2 = chunk "IHDR", buf
imagebuf = new Buffer height * (width * 3 +1)
pos = 0
data.map (line) ->
d = [0].concat line... # http://stackoverflow.com/questions/4631525/
d.map (c) -> imagebuf.writeUInt8 c, pos++
zlib.deflate imagebuf, (err, res) ->
return if err
buf3 = chunk "IDAT", new Buffer res, 'ascii'
buf4 = chunk "IEND", new Buffer ""
buf = new Buffer 33+buf3.length+buf4.length
buf1.copy buf, 0
buf2.copy buf, 8
buf3.copy buf, 33
buf4.copy buf, 33 + buf3.length
callback buf
module.exports = PNG
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.