2 libimago - a multi-format image file input/output library.
3 Copyright (C) 2010 John Tsiombikas <nuclear@member.fsf.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published
7 by the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 /* -- Portable Pixmap (PPM) module -- */
23 #include "ftype_module.h"
25 static int check(struct img_io *io);
26 static int read(struct img_pixmap *img, struct img_io *io);
27 static int write(struct img_pixmap *img, struct img_io *io);
29 int img_register_ppm(void)
31 static struct ftype_module mod = {".ppm", check, read, write};
32 return img_register_module(&mod);
36 static int check(struct img_io *io)
40 long pos = io->seek(0, SEEK_CUR, io->uptr);
42 if(io->read(id, 2, io->uptr) < 2) {
43 io->seek(pos, SEEK_SET, io->uptr);
47 if(id[0] == 'P' && (id[1] == '6' || id[1] == '3')) {
50 io->seek(pos, SEEK_SET, io->uptr);
54 static int iofgetc(struct img_io *io)
57 return io->read(&c, 1, io->uptr) < 1 ? -1 : c;
60 static char *iofgets(char *buf, int size, struct img_io *io)
65 while(--size > 0 && (c = iofgetc(io)) != -1) {
71 return ptr == buf ? 0 : buf;
74 /* TODO: implement P3 reading */
75 static int read(struct img_pixmap *img, struct img_io *io)
78 int xsz, ysz, maxval, got_hdrlines = 1;
80 if(!iofgets(buf, sizeof buf, io)) {
83 if(!(buf[0] == 'P' && (buf[1] == '6' || buf[1] == '3'))) {
87 while(got_hdrlines < 3 && iofgets(buf, sizeof buf, io)) {
88 if(buf[0] == '#') continue;
90 switch(got_hdrlines) {
92 if(sscanf(buf, "%d %d\n", &xsz, &ysz) < 2) {
98 if(sscanf(buf, "%d\n", &maxval) < 1) {
107 if(xsz < 1 || ysz < 1 || maxval != 255) {
111 if(img_set_pixels(img, xsz, ysz, IMG_FMT_RGB24, 0) == -1) {
115 if(io->read(img->pixels, xsz * ysz * 3, io->uptr) < (unsigned int)(xsz * ysz * 3)) {
121 static int write(struct img_pixmap *img, struct img_io *io)
125 struct img_pixmap tmpimg;
129 if(img->fmt != IMG_FMT_RGB24) {
130 if(img_copy(&tmpimg, img) == -1) {
133 if(img_convert(&tmpimg, IMG_FMT_RGB24) == -1) {
139 sprintf(buf, "P6\n#written by libimago2\n%d %d\n255\n", img->width, img->height);
140 if(io->write(buf, strlen(buf), io->uptr) < strlen(buf)) {
141 img_destroy(&tmpimg);
145 sz = img->width * img->height * 3;
146 if(io->write(img->pixels, sz, io->uptr) < (unsigned int)sz) {
147 img_destroy(&tmpimg);
151 img_destroy(&tmpimg);