1 /* based on PNG 1.2 specification, July 1999 (see also rfc2083) */
2 /* Alpha is not supported yet because of lack of industry acceptance and */
3 /* because Plan9 Image uses premultiplied alpha, so png can't be lossless. */
4 /* Only 24bit color supported, because 8bit may as well use GIF. */
13 #include "imagefile.h"
15 enum{ IDATSIZE = 20000,
23 int row, col; /* next pixel to send */
30 uchar *b; /* next place to write */
31 uchar *e; /* past end of buf */
34 static uint32 *crctab;
35 static uchar PNGmagic[] = {137,80,78,71,13,10,26,10};
38 put4(uchar *a, uint32 v)
47 chunk(Biobuf *bo, char *type, uchar *d, int n)
58 crc = blockcrc(crctab, crc, type, 4);
59 crc = blockcrc(crctab, crc, d, n);
65 zread(void *va, void *buf, int n)
70 uchar *b = buf, *e = b+n, *img;
71 int pixels; /* number of pixels in row that can be sent now */
75 while(b+pixwid <= e){ /* loop over image rows */
80 pixels = (e-b)/pixwid;
81 if(pixels > ncol - z->col)
82 pixels = ncol - z->col;
83 img = z->data + z->width * z->row + pixwid * z->col;
85 memmove(b, img, pixwid*pixels);
88 * Convert to non-premultiplied alpha.
90 for(i=0; i<pixels; i++, b+=4){
92 if(a == 255 || a == 0)
115 return b - (uchar*)buf;
121 chunk(z->bo, "IDAT", z->buf, z->b - z->buf);
126 zwrite(void *va, void *buf, int n)
129 uchar *b = buf, *e = b+n;
132 while(b < e){ /* loop over IDAT chunks */
153 * [A]BGR because we want R,G,B,[A] in big-endian order. Sigh.
155 chantostr(buf, i->chan);
164 ni = allocmemimage(i->r, dst);
167 memimagedraw(ni, ni->r, i, i->r.min, nil, i->r.min, S);
172 memwritepng(Biobuf *bo, Memimage *r, ImageInfo *II)
179 int nrow = r->r.max.y - r->r.min.y;
180 int ncol = r->r.max.x - r->r.min.x;
186 return "allocmemimage nil";
187 crctab = mkcrctab(0xedb88320);
189 sysfatal("mkcrctab error");
192 Bwrite(bo, PNGmagic, sizeof PNGmagic);
195 put4(h, ncol); h += 4;
196 put4(h, nrow); h += 4;
197 *h++ = 8; /* bit depth = 24 bit per pixel */
198 *h++ = rgb->chan==BGR24 ? 2 : 6; /* color type = rgb */
199 *h++ = 0; /* compression method = deflate */
200 *h++ = 0; /* filter method */
201 *h++ = 0; /* interlace method = no interlace */
202 chunk(bo, "IHDR", buf, h-buf);
204 tm = gmtime(time(0));
206 *h++ = (tm->year + 1900)>>8;
207 *h++ = (tm->year + 1900)&0xff;
213 chunk(bo, "tIME", buf, h-buf);
215 if(II->fields_set & II_GAMMA){
216 vgamma = II->gamma*100000;
218 chunk(bo, "gAMA", buf, 4);
221 if(II->fields_set & II_COMMENT){
222 strncpy((char*)buf, "Comment", sizeof buf);
223 n = strlen((char*)buf)+1; /* leave null between Comment and text */
224 strncpy((char*)(buf+n), II->comment, sizeof buf - n);
225 chunk(bo, "tEXt", buf, n+strlen((char*)buf+n));
231 zr.width = rgb->width * sizeof(uint32);
232 zr.data = rgb->data->bdata;
234 zr.pixwid = chantodepth(rgb->chan)/8;
236 zw.buf = malloc(IDATSIZE);
238 zw.e = zw.b + IDATSIZE;
239 err = deflatezlib(&zw, zwrite, &zr, zread, 6, 0);
244 sysfatal("deflatezlib %s\n", flateerr(err));
245 chunk(bo, "IEND", nil, 0);