1 /* Copyright (C) 2001-2012 Artifex Software, Inc.
4 This software is provided AS-IS with no warranty, either express or
7 This software is distributed under license and may not be copied,
8 modified or distributed except as expressly authorized under the terms
9 of the license contained in the file LICENSE in this distribution.
11 Refer to licensing information at http://www.artifex.com or contact
12 Artifex Software, Inc., 7 Mt. Lassen Drive - Suite A-134, San Rafael,
13 CA 94903, U.S.A., +1(415)492-9861, for further information.
30 #include "jbig2_priv.h"
31 #include "jbig2_image.h"
33 /* take an image structure and write it to a file in pbm format */
35 int jbig2_image_write_pbm_file(Jbig2Image *image, char *filename)
40 if ((out = fopen(filename, "wb")) == NULL) {
41 fprintf(stderr, "unable to open '%s' for writing", filename);
45 error = jbig2_image_write_pbm(image, out);
51 /* write out an image struct as a pbm stream to an open file pointer */
53 int jbig2_image_write_pbm(Jbig2Image *image, FILE *out)
56 fprintf(out, "P4\n%d %d\n", image->width, image->height);
58 /* pbm format pads to a byte boundary, so we can
59 just write out the whole data buffer
60 NB: this assumes minimal stride for the width */
61 fwrite(image->data, 1, image->height*image->stride, out);
67 /* take an image from a file in pbm format */
68 Jbig2Image *jbig2_image_read_pbm_file(Jbig2Ctx *ctx, char *filename)
73 if ((in = fopen(filename, "rb")) == NULL) {
74 fprintf(stderr, "unable to open '%s' for reading\n", filename);
78 image = jbig2_image_read_pbm(ctx, in);
85 /* FIXME: should handle multi-image files */
86 Jbig2Image *jbig2_image_read_pbm(Jbig2Ctx *ctx, FILE *in)
94 /* look for 'P4' magic */
95 while ((c = fgetc(in)) != 'P') {
96 if (feof(in)) return NULL;
98 if ((c = fgetc(in)) != '4') {
99 fprintf(stderr, "not a binary pbm file.\n");
102 /* read size. we must find two decimal numbers representing
103 the image dimensions. 'done' will index whether we're
104 looking for the width or the height and 'i' will be our
105 array index for copying strings into our buffer */
110 /* skip whitespace */
111 if (c == ' ' || c == '\t' || c == '\r' || c == '\n') continue;
114 while ((c = fgetc(in)) != '\n');
117 /* report unexpected eof */
119 fprintf(stderr, "end-of-file parsing pbm header\n");
124 while (isdigit(c = fgetc(in))) {
126 fprintf(stderr, "pbm parsing error\n");
132 if (sscanf(buf, "%d", &dim[done]) != 1) {
133 fprintf(stderr, "couldn't read pbm image dimensions\n");
140 /* allocate image structure */
141 image = jbig2_image_new(ctx, dim[0], dim[1]);
143 fprintf(stderr, "could not allocate %dx%d image for pbm file\n", dim[0], dim[1]);
146 /* the pbm data is byte-aligned, so we can
147 do a simple block read */
148 fread(image->data, 1, image->height*image->stride, in);
150 fprintf(stderr, "unexpected end of pbm file.\n");
151 jbig2_image_release(ctx, image);