9 /* imported from libdraw/arith.c to permit an extern log2 function */
11 -1, 0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, 4,
12 -1, -1, -1, -1, -1, -1, -1, 4 /* BUG */, -1, -1, -1, -1, -1, -1, -1, 5
20 Bputbit(Biobufhdr *b, int c)
23 bitc = (bitc << 1) | (c & 0x1);
26 for(; nbit < 8; nbit++)
40 writedata(Biobuf *fd, Image *image, Memimage *memimage, int rflag)
44 int i, x, y, ndata, depth, col, pix, xmask, pmask;
50 depth = memimage->depth;
51 chan = memimage->chan;
59 * Read image data into memory
60 * potentially one extra byte on each end of each scan line
62 ndata = Dy(r)*(2+Dx(r)*depth/8);
65 return "WritePPM: malloc failed";
67 ndata = unloadmemimage(memimage, r, data, ndata);
69 ndata = unloadimage(image, r, data, ndata);
73 return "WritePPM: malloc failed";
74 snprint(err, ERRMAX, "WritePPM: %r");
79 /* Encode and emit the data */
86 xmask = 7>>log2[depth];
87 for(y=r.min.y; y<r.max.y; y++){
88 i = (y-r.min.y)*bytesperline(r, depth);
89 for(x=r.min.x; x<r.max.x; x++){
90 pix = (data[i]>>depth*((xmask-x)&xmask))&pmask;
91 if(((x+1)&xmask) == 0)
105 col += Bprint(fd, "%d", pix);
106 if(col >= MAXLINE-(2+1)){
110 col += Bprint(fd, " ");
117 for(i=0; i<ndata; i++){
122 col += Bprint(fd, "%d", data[i]);
123 if(col >= MAXLINE-(4+1)){
127 col += Bprint(fd, " ");
131 for(i=0; i<ndata; i+=3){
133 Bputc(fd, data[i+2]);
134 Bputc(fd, data[i+1]);
138 col += Bprint(fd, "%d %d %d", data[i+2], data[i+1], data[i]);
139 if(col >= MAXLINE-(4+4+4+1)){
143 col += Bprint(fd, " ");
147 return "WritePPM: can't handle channel type";
155 writeppm0(Biobuf *fd, Image *image, Memimage *memimage, Rectangle r, int chan, char *comment, int rflag)
161 Bprint(fd, "%s\n", rflag? "P4": "P1");
166 Bprint(fd, "%s\n", rflag? "P5": "P2");
169 Bprint(fd, "%s\n", rflag? "P6": "P3");
172 return "WritePPM: can't handle channel type";
175 if(comment!=nil && comment[0]!='\0'){
176 Bprint(fd, "# %s", comment);
177 if(comment[strlen(comment)-1] != '\n')
180 Bprint(fd, "%d %d\n", Dx(r), Dy(r));
182 /* maximum pixel value */
185 Bprint(fd, "%d\n", 3);
188 Bprint(fd, "%d\n", 15);
192 Bprint(fd, "%d\n", 255);
196 err = writedata(fd, image, memimage, rflag);
205 writeppm(Biobuf *fd, Image *image, char *comment, int rflag)
207 return writeppm0(fd, image, nil, image->r, image->chan, comment, rflag);
211 memwriteppm(Biobuf *fd, Memimage *memimage, char *comment, int rflag)
213 return writeppm0(fd, nil, memimage, memimage->r, memimage->chan, comment, rflag);