Define _CRT_NONSTDC_NO_WARNINGS for zlib compilation with MSVC.
[wxWidgets.git] / src / tiff / tools / tiff2ps.c
1
2 /*
3 * Copyright (c) 1988-1997 Sam Leffler
4 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
5 *
6 * Permission to use, copy, modify, distribute, and sell this software and
7 * its documentation for any purpose is hereby granted without fee, provided
8 * that (i) the above copyright notices and this permission notice appear in
9 * all copies of the software and related documentation, and (ii) the names of
10 * Sam Leffler and Silicon Graphics may not be used in any advertising or
11 * publicity relating to the software without the specific, prior written
12 * permission of Sam Leffler and Silicon Graphics.
13 *
14 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
16 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
17 *
18 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
19 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
20 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
21 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
22 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
23 * OF THIS SOFTWARE.
24 */
25
26 #include "tif_config.h"
27
28 #include <stdio.h>
29 #include <stdlib.h> /* for atof */
30 #include <math.h>
31 #include <time.h>
32 #include <string.h>
33
34 #ifdef HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37
38 #ifdef NEED_LIBPORT
39 # include "libport.h"
40 #endif
41
42 #include "tiffio.h"
43
44 /*
45 * Revision history
46 *
47 * 2010-Sep-17
48 * Richard Nolde: Reinstate code from Feb 2009 that never got
49 * accepted into CVS with major modifications to handle -H and -W
50 * options. Replaced original PlaceImage function with several
51 * new functions that make support for multiple output pages
52 * from a single image easier to understand. Added additional
53 * warning messages for incompatible command line options.
54 * Add new command line options to specify PageOrientation
55 * Document Structuring Comment for landscape or portrait
56 * and code to determine the values from ouput width and height
57 * if not specified on the command line.
58 * Add new command line option to specify document creator
59 * as an alterntive to the string "tiff2ps" following model
60 * of patch submitted by Thomas Jarosch for specifiying a
61 * document title which is also supported now.
62 *
63 * 2009-Feb-11
64 * Richard Nolde: Added support for rotations of 90, 180, 270
65 * and auto using -r <90|180|270|auto>. Auto picks the best
66 * fit for the image on the specified paper size (eg portrait
67 * or landscape) if -h or -w is specified. Rotation is in
68 * degrees counterclockwise since that is how Postscript does
69 * it. The auto opption rotates the image 90 degrees ccw to
70 * produce landscape if that is a better fit than portait.
71 *
72 * Cleaned up code in TIFF2PS and broke into smaller functions
73 * to simplify rotations.
74 *
75 * Identified incompatible options and returned errors, eg
76 * -i for imagemask operator is only available for Level2 or
77 * Level3 Postscript in the current implmentation since there
78 * is a difference in the way the operands are called for Level1
79 * and there is no function to provide the Level1 version.
80 * -H was not handled properly if -h and/or -w were specified.
81 * It should only clip the masked images if the scaled image
82 * exceeds the maxPageHeight specified with -H.
83 *
84 * New design allows for all of the following combinations:
85 * Conversion of TIFF to Postscript with optional rotations
86 * of 90, 180, 270, or auto degrees counterclockwise
87 * Conversion of TIFF to Postscript with entire image scaled
88 * to maximum of values spedified with -h or -w while
89 * maintaining aspect ratio. Same rotations apply.
90 * Conversion of TIFF to Postscript with clipping of output
91 * viewport to height specified with -H, producing multiple
92 * pages at this height and original width as needed.
93 * Same rotations apply.
94 * Conversion of TIFF to Postscript with image scaled to
95 * maximum specified by -h and -w and the resulting scaled
96 * image is presented in an output viewport clipped by -H height.
97 * The same rotations apply.
98 *
99 * Added maxPageWidth option using -W flag. MaxPageHeight and
100 * MaxPageWidth are mutually exclusive since the aspect ratio
101 * cannot be maintained if you set both.
102 * Rewrote PlaceImage to allow maxPageHeight and maxPageWidth
103 * options to work with values smaller or larger than the
104 * physical paper size and still preserve the aspect ratio.
105 * This is accomplished by creating multiple pages across
106 * as well as down if need be.
107 *
108 * 2001-Mar-21
109 * I (Bruce A. Mallett) added this revision history comment ;)
110 *
111 * Fixed PS_Lvl2page() code which outputs non-ASCII85 raw
112 * data. Moved test for when to output a line break to
113 * *after* the output of a character. This just serves
114 * to fix an eye-nuisance where the first line of raw
115 * data was one character shorter than subsequent lines.
116 *
117 * Added an experimental ASCII85 encoder which can be used
118 * only when there is a single buffer of bytes to be encoded.
119 * This version is much faster at encoding a straight-line
120 * buffer of data because it can avoid a lot of the loop
121 * overhead of the byte-by-byte version. To use this version
122 * you need to define EXP_ASCII85ENCODER (experimental ...).
123 *
124 * Added bug fix given by Michael Schmidt to PS_Lvl2page()
125 * in which an end-of-data marker ('>') was not being output
126 * when producing non-ASCII85 encoded PostScript Level 2
127 * data.
128 *
129 * Fixed PS_Lvl2colorspace() so that it no longer assumes that
130 * a TIFF having more than 2 planes is a CMYK. This routine
131 * no longer looks at the samples per pixel but instead looks
132 * at the "photometric" value. This change allows support of
133 * CMYK TIFFs.
134 *
135 * Modified the PostScript L2 imaging loop so as to test if
136 * the input stream is still open before attempting to do a
137 * flushfile on it. This was done because some RIPs close
138 * the stream after doing the image operation.
139 *
140 * Got rid of the realloc() being done inside a loop in the
141 * PSRawDataBW() routine. The code now walks through the
142 * byte-size array outside the loop to determine the largest
143 * size memory block that will be needed.
144 *
145 * Added "-m" switch to ask tiff2ps to, where possible, use the
146 * "imagemask" operator instead of the "image" operator.
147 *
148 * Added the "-i #" switch to allow interpolation to be disabled.
149 *
150 * Unrolled a loop or two to improve performance.
151 */
152
153 /*
154 * Define EXP_ASCII85ENCODER if you want to use an experimental
155 * version of the ASCII85 encoding routine. The advantage of
156 * using this routine is that tiff2ps will convert to ASCII85
157 * encoding at between 3 and 4 times the speed as compared to
158 * using the old (non-experimental) encoder. The disadvantage
159 * is that you will be using a new (and unproven) encoding
160 * routine. So user beware, you have been warned!
161 */
162
163 #define EXP_ASCII85ENCODER
164
165 /*
166 * NB: this code assumes uint32 works with printf's %l[ud].
167 */
168 #ifndef TRUE
169 #define TRUE 1
170 #define FALSE 0
171 #endif
172
173 int ascii85 = FALSE; /* use ASCII85 encoding */
174 int interpolate = TRUE; /* interpolate level2 image */
175 int level2 = FALSE; /* generate PostScript level 2 */
176 int level3 = FALSE; /* generate PostScript level 3 */
177 int printAll = FALSE; /* print all images in file */
178 int generateEPSF = TRUE; /* generate Encapsulated PostScript */
179 int PSduplex = FALSE; /* enable duplex printing */
180 int PStumble = FALSE; /* enable top edge binding */
181 int PSavoiddeadzone = TRUE; /* enable avoiding printer deadzone */
182 double maxPageHeight = 0; /* maximum height to select from image and print per page */
183 double maxPageWidth = 0; /* maximum width to select from image and print per page */
184 double splitOverlap = 0; /* amount for split pages to overlag */
185 int rotation = 0; /* optional value for rotation angle */
186 int auto_rotate = 0; /* rotate image for best fit on the page */
187 char *filename = NULL; /* input filename */
188 char *title = NULL; /* optional document title string */
189 char *creator = NULL; /* optional document creator string */
190 char pageOrientation[12]; /* set optional PageOrientation DSC to Landscape or Portrait */
191 int useImagemask = FALSE; /* Use imagemask instead of image operator */
192 uint16 res_unit = 0; /* Resolution units: 2 - inches, 3 - cm */
193
194 /*
195 * ASCII85 Encoding Support.
196 */
197 unsigned char ascii85buf[10];
198 int ascii85count;
199 int ascii85breaklen;
200
201 int TIFF2PS(FILE*, TIFF*, double, double, double, double, int);
202 void PSpage(FILE*, TIFF*, uint32, uint32);
203 void PSColorContigPreamble(FILE*, uint32, uint32, int);
204 void PSColorSeparatePreamble(FILE*, uint32, uint32, int);
205 void PSDataColorContig(FILE*, TIFF*, uint32, uint32, int);
206 void PSDataColorSeparate(FILE*, TIFF*, uint32, uint32, int);
207 void PSDataPalette(FILE*, TIFF*, uint32, uint32);
208 void PSDataBW(FILE*, TIFF*, uint32, uint32);
209 void PSRawDataBW(FILE*, TIFF*, uint32, uint32);
210 void Ascii85Init(void);
211 void Ascii85Put(unsigned char code, FILE* fd);
212 void Ascii85Flush(FILE* fd);
213 void PSHead(FILE*, double, double, double, double);
214 void PSTail(FILE*, int);
215 int psStart(FILE *, int, int, int *, double *, double, double, double,
216 double, double, double, double, double, double, double);
217 int psPageSize(FILE *, int, double, double, double, double, double, double);
218 int psRotateImage(FILE *, int, double, double, double, double);
219 int psMaskImage(FILE *, TIFF *, int, int, int *, double, double,
220 double, double, double, double, double, double, double);
221 int psScaleImage(FILE *, double, int, int, double, double, double, double,
222 double, double);
223 int get_viewport (double, double, double, double, double *, double *, int);
224 int exportMaskedImage(FILE *, double, double, double, double, int, int,
225 double, double, double, int, int);
226
227 #if defined( EXP_ASCII85ENCODER)
228 tsize_t Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, tsize_t raw_l );
229 #endif
230
231 static void usage(int);
232
233 int
234 main(int argc, char* argv[])
235 {
236 int dirnum = -1, c, np = 0;
237 int centered = 0;
238 double bottommargin = 0;
239 double leftmargin = 0;
240 double pageWidth = 0;
241 double pageHeight = 0;
242 uint32 diroff = 0;
243 extern char *optarg;
244 extern int optind;
245 FILE* output = stdout;
246
247 pageOrientation[0] = '\0';
248
249 while ((c = getopt(argc, argv, "b:d:h:H:W:L:i:w:l:o:O:P:C:r:t:acemxyzps1238DT")) != -1)
250 switch (c) {
251 case 'b':
252 bottommargin = atof(optarg);
253 break;
254 case 'c':
255 centered = 1;
256 break;
257 case 'C':
258 creator = optarg;
259 break;
260 case 'd': /* without -a, this only processes one image at this IFD */
261 dirnum = atoi(optarg);
262 break;
263 case 'D':
264 PSduplex = TRUE;
265 break;
266 case 'i':
267 interpolate = atoi(optarg) ? TRUE:FALSE;
268 break;
269 case 'T':
270 PStumble = TRUE;
271 break;
272 case 'e':
273 PSavoiddeadzone = FALSE;
274 generateEPSF = TRUE;
275 break;
276 case 'h':
277 pageHeight = atof(optarg);
278 break;
279 case 'H':
280 maxPageHeight = atof(optarg);
281 break;
282 case 'W':
283 maxPageWidth = atof(optarg);
284 break;
285 case 'L':
286 splitOverlap = atof(optarg);
287 break;
288 case 'm':
289 useImagemask = TRUE;
290 break;
291 case 'o':
292 switch (optarg[0])
293 {
294 case '0':
295 case '1':
296 case '2':
297 case '3':
298 case '4':
299 case '5':
300 case '6':
301 case '7':
302 case '8':
303 case '9': diroff = (uint32) strtoul(optarg, NULL, 0);
304 break;
305 default: TIFFError ("-o", "Offset must be a numeric value.");
306 exit (1);
307 }
308 break;
309 case 'O': /* XXX too bad -o is already taken */
310 output = fopen(optarg, "w");
311 if (output == NULL) {
312 fprintf(stderr,
313 "%s: %s: Cannot open output file.\n",
314 argv[0], optarg);
315 exit(-2);
316 }
317 break;
318 case 'P':
319 switch (optarg[0])
320 {
321 case 'l':
322 case 'L': strcpy (pageOrientation, "Landscape");
323 break;
324 case 'p':
325 case 'P': strcpy (pageOrientation, "Portrait");
326 break;
327 default: TIFFError ("-P", "Page orientation must be Landscape or Portrait");
328 exit (-1);
329 }
330 break;
331 case 'l':
332 leftmargin = atof(optarg);
333 break;
334 case 'a': /* removed fall through to generate warning below, R Nolde 09-01-2010 */
335 printAll = TRUE;
336 break;
337 case 'p':
338 generateEPSF = FALSE;
339 break;
340 case 'r':
341 if (strcmp (optarg, "auto") == 0)
342 {
343 rotation = 0;
344 auto_rotate = TRUE;
345 }
346 else
347 {
348 rotation = atoi(optarg);
349 auto_rotate = FALSE;
350 }
351 switch (rotation)
352 {
353 case 0:
354 case 90:
355 case 180:
356 case 270:
357 break;
358 default:
359 fprintf (stderr, "Rotation angle must be 90, 180, 270 (degrees ccw) or auto\n");
360 exit (-1);
361 }
362 break;
363 case 's':
364 printAll = FALSE;
365 break;
366 case 't':
367 title = optarg;
368 break;
369 case 'w':
370 pageWidth = atof(optarg);
371 break;
372 case 'z':
373 PSavoiddeadzone = FALSE;
374 break;
375 case '1':
376 level2 = FALSE;
377 level3 = FALSE;
378 ascii85 = FALSE;
379 break;
380 case '2':
381 level2 = TRUE;
382 ascii85 = TRUE; /* default to yes */
383 break;
384 case '3':
385 level3 = TRUE;
386 ascii85 = TRUE; /* default to yes */
387 break;
388 case '8':
389 ascii85 = FALSE;
390 break;
391 case 'x':
392 res_unit = RESUNIT_CENTIMETER;
393 break;
394 case 'y':
395 res_unit = RESUNIT_INCH;
396 break;
397 case '?':
398 usage(-1);
399 }
400
401 if (useImagemask == TRUE)
402 {
403 if ((level2 == FALSE) && (level3 == FALSE))
404 {
405 TIFFError ("-m "," imagemask operator requres Postscript Level2 or Level3");
406 exit (1);
407 }
408 }
409
410 if (pageWidth && (maxPageWidth > pageWidth))
411 {
412 TIFFError ("-W", "Max viewport width cannot exceed page width");
413 exit (1);
414 }
415
416 if (pageHeight && (maxPageHeight > pageHeight))
417 {
418 TIFFError ("-H", "Max viewport height cannot exceed page height");
419 exit (1);
420 }
421
422 /* auto rotate requires a specified page width and height */
423 if (auto_rotate == TRUE)
424 {
425 if ((pageWidth == 0) || (pageHeight == 0))
426 TIFFWarning ("-r auto", " requires page height and width specified with -h and -w");
427
428 if ((maxPageWidth > 0) || (maxPageHeight > 0))
429 {
430 TIFFError ("-r auto", " is incompatible with maximum page width/height specified by -H or -W");
431 exit (1);
432 }
433 }
434 if ((maxPageWidth > 0) && (maxPageHeight > 0))
435 {
436 TIFFError ("-H and -W", " Use only one of -H or -W to define a viewport");
437 exit (1);
438 }
439
440 if ((generateEPSF == TRUE) && (printAll == TRUE))
441 {
442 TIFFError(" -e and -a", "Warning: Cannot generate Encapsulated Postscript for multiple images");
443 generateEPSF = FALSE;
444 }
445
446 if ((generateEPSF == TRUE) && (PSduplex == TRUE))
447 {
448 TIFFError(" -e and -D", "Warning: Encapsulated Postscript does not support Duplex option");
449 PSduplex = FALSE;
450 }
451
452 if ((generateEPSF == TRUE) && (PStumble == TRUE))
453 {
454 TIFFError(" -e and -T", "Warning: Encapsulated Postscript does not support Top Edge Binding option");
455 PStumble = FALSE;
456 }
457
458 if ((generateEPSF == TRUE) && (PSavoiddeadzone == TRUE))
459 PSavoiddeadzone = FALSE;
460
461 for (; argc - optind > 0; optind++) {
462 TIFF* tif = TIFFOpen(filename = argv[optind], "r");
463 if (tif != NULL) {
464 if (dirnum != -1
465 && !TIFFSetDirectory(tif, (tdir_t)dirnum))
466 return (-1);
467 else if (diroff != 0 &&
468 !TIFFSetSubDirectory(tif, diroff))
469 return (-1);
470 np = TIFF2PS(output, tif, pageWidth, pageHeight,
471 leftmargin, bottommargin, centered);
472 if (np < 0)
473 {
474 TIFFError("Error", "Unable to process %s", filename);
475 }
476 TIFFClose(tif);
477 }
478 }
479 if (np)
480 PSTail(output, np);
481 else
482 usage(-1);
483 if (output != stdout)
484 fclose(output);
485 return (0);
486 }
487
488 static uint16 samplesperpixel;
489 static uint16 bitspersample;
490 static uint16 planarconfiguration;
491 static uint16 photometric;
492 static uint16 compression;
493 static uint16 extrasamples;
494 static int alpha;
495
496 static int
497 checkImage(TIFF* tif)
498 {
499 switch (photometric) {
500 case PHOTOMETRIC_YCBCR:
501 if ((compression == COMPRESSION_JPEG || compression == COMPRESSION_OJPEG)
502 && planarconfiguration == PLANARCONFIG_CONTIG) {
503 /* can rely on libjpeg to convert to RGB */
504 TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE,
505 JPEGCOLORMODE_RGB);
506 photometric = PHOTOMETRIC_RGB;
507 } else {
508 if (level2 || level3)
509 break;
510 TIFFError(filename, "Can not handle image with %s",
511 "PhotometricInterpretation=YCbCr");
512 return (0);
513 }
514 /* fall thru... */
515 case PHOTOMETRIC_RGB:
516 if (alpha && bitspersample != 8) {
517 TIFFError(filename,
518 "Can not handle %d-bit/sample RGB image with alpha",
519 bitspersample);
520 return (0);
521 }
522 /* fall thru... */
523 case PHOTOMETRIC_SEPARATED:
524 case PHOTOMETRIC_PALETTE:
525 case PHOTOMETRIC_MINISBLACK:
526 case PHOTOMETRIC_MINISWHITE:
527 break;
528 case PHOTOMETRIC_LOGL:
529 case PHOTOMETRIC_LOGLUV:
530 if (compression != COMPRESSION_SGILOG &&
531 compression != COMPRESSION_SGILOG24) {
532 TIFFError(filename,
533 "Can not handle %s data with compression other than SGILog",
534 (photometric == PHOTOMETRIC_LOGL) ?
535 "LogL" : "LogLuv"
536 );
537 return (0);
538 }
539 /* rely on library to convert to RGB/greyscale */
540 TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT);
541 photometric = (photometric == PHOTOMETRIC_LOGL) ?
542 PHOTOMETRIC_MINISBLACK : PHOTOMETRIC_RGB;
543 bitspersample = 8;
544 break;
545 case PHOTOMETRIC_CIELAB:
546 /* fall thru... */
547 default:
548 TIFFError(filename,
549 "Can not handle image with PhotometricInterpretation=%d",
550 photometric);
551 return (0);
552 }
553 switch (bitspersample) {
554 case 1: case 2:
555 case 4: case 8:
556 case 16:
557 break;
558 default:
559 TIFFError(filename, "Can not handle %d-bit/sample image",
560 bitspersample);
561 return (0);
562 }
563 if (planarconfiguration == PLANARCONFIG_SEPARATE && extrasamples > 0)
564 TIFFWarning(filename, "Ignoring extra samples");
565 return (1);
566 }
567
568 #define PS_UNIT_SIZE 72.0F
569 #define PSUNITS(npix,res) ((npix) * (PS_UNIT_SIZE / (res)))
570
571 static char RGBcolorimage[] = "\
572 /bwproc {\n\
573 rgbproc\n\
574 dup length 3 idiv string 0 3 0\n\
575 5 -1 roll {\n\
576 add 2 1 roll 1 sub dup 0 eq {\n\
577 pop 3 idiv\n\
578 3 -1 roll\n\
579 dup 4 -1 roll\n\
580 dup 3 1 roll\n\
581 5 -1 roll put\n\
582 1 add 3 0\n\
583 } { 2 1 roll } ifelse\n\
584 } forall\n\
585 pop pop pop\n\
586 } def\n\
587 /colorimage where {pop} {\n\
588 /colorimage {pop pop /rgbproc exch def {bwproc} image} bind def\n\
589 } ifelse\n\
590 ";
591
592 /*
593 * Adobe Photoshop requires a comment line of the form:
594 *
595 * %ImageData: <cols> <rows> <depth> <main channels> <pad channels>
596 * <block size> <1 for binary|2 for hex> "data start"
597 *
598 * It is claimed to be part of some future revision of the EPS spec.
599 */
600 static void
601 PhotoshopBanner(FILE* fd, uint32 w, uint32 h, int bs, int nc, char* startline)
602 {
603 fprintf(fd, "%%ImageData: %ld %ld %d %d 0 %d 2 \"",
604 (long) w, (long) h, bitspersample, nc, bs);
605 fprintf(fd, startline, nc);
606 fprintf(fd, "\"\n");
607 }
608
609 /* Convert pixel width and height pw, ph, to points pprw, pprh
610 * using image resolution and resolution units from TIFF tags.
611 * pw : image width in pixels
612 * ph : image height in pixels
613 * pprw : image width in PS units (72 dpi)
614 * pprh : image height in PS units (72 dpi)
615 */
616 static void
617 setupPageState(TIFF* tif, uint32* pw, uint32* ph, double* pprw, double* pprh)
618 {
619 float xres = 0.0F, yres = 0.0F;
620
621 TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, pw);
622 TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ph);
623 if (res_unit == 0) /* Not specified as command line option */
624 if (!TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &res_unit))
625 res_unit = RESUNIT_INCH;
626 /*
627 * Calculate printable area.
628 */
629 if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres)
630 || fabs(xres) < 0.0000001)
631 xres = PS_UNIT_SIZE;
632 if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres)
633 || fabs(yres) < 0.0000001)
634 yres = PS_UNIT_SIZE;
635 switch (res_unit) {
636 case RESUNIT_CENTIMETER:
637 xres *= 2.54F, yres *= 2.54F;
638 break;
639 case RESUNIT_INCH:
640 break;
641 case RESUNIT_NONE: /* Subsequent code assumes we have converted to inches! */
642 res_unit = RESUNIT_INCH;
643 break;
644 default: /* Last ditch guess for unspecified RESUNIT case
645 * check that the resolution is not inches before scaling it.
646 * Moved to end of function with additional check, RJN, 08-31-2010
647 * if (xres != PS_UNIT_SIZE || yres != PS_UNIT_SIZE)
648 * xres *= PS_UNIT_SIZE, yres *= PS_UNIT_SIZE;
649 */
650 break;
651 }
652 /* This is a hack to deal with images that have no meaningful Resolution Size
653 * but may have x and/or y resolutions of 1 pixel per undefined unit.
654 */
655 if ((xres > 1.0) && (xres != PS_UNIT_SIZE))
656 *pprw = PSUNITS(*pw, xres);
657 else
658 *pprw = PSUNITS(*pw, PS_UNIT_SIZE);
659 if ((yres > 1.0) && (yres != PS_UNIT_SIZE))
660 *pprh = PSUNITS(*ph, yres);
661 else
662 *pprh = PSUNITS(*ph, PS_UNIT_SIZE);
663 }
664
665 static int
666 isCCITTCompression(TIFF* tif)
667 {
668 uint16 compress;
669 TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress);
670 return (compress == COMPRESSION_CCITTFAX3 ||
671 compress == COMPRESSION_CCITTFAX4 ||
672 compress == COMPRESSION_CCITTRLE ||
673 compress == COMPRESSION_CCITTRLEW);
674 }
675
676 static tsize_t tf_bytesperrow;
677 static tsize_t ps_bytesperrow;
678 static tsize_t tf_rowsperstrip;
679 static tsize_t tf_numberstrips;
680 static char *hex = "0123456789abcdef";
681
682 /*
683 * Pagewidth and pageheight are the output size in points,
684 * may refer to values specified with -h and -w, or to
685 * values read from the image if neither -h nor -w are used.
686 * Imagewidth and imageheight are image size in points.
687 * Ximages and Yimages are number of pages across and down.
688 * Only one of maxPageHeight or maxPageWidth can be used.
689 * These are global variables unfortunately.
690 */
691 int get_subimage_count(double pagewidth, double pageheight,
692 double imagewidth, double imageheight,
693 int *ximages, int *yimages,
694 int rotation, double scale)
695 {
696 int pages = 1;
697 double splitheight = 0; /* Requested Max Height in points */
698 double splitwidth = 0; /* Requested Max Width in points */
699 double overlap = 0; /* Repeated edge width in points */
700
701 splitheight = maxPageHeight * PS_UNIT_SIZE;
702 splitwidth = maxPageWidth * PS_UNIT_SIZE;
703 overlap = splitOverlap * PS_UNIT_SIZE;
704 pagewidth *= PS_UNIT_SIZE;
705 pageheight *= PS_UNIT_SIZE;
706
707 if ((imagewidth < 1.0) || (imageheight < 1.0))
708 {
709 TIFFError("get_subimage_count", "Invalid image width or height");
710 return (0);
711 }
712
713 switch (rotation)
714 {
715 case 0:
716 case 180: if (splitheight > 0) /* -H maxPageHeight */
717 {
718 if (imageheight > splitheight) /* More than one vertical image segment */
719 {
720 if (pagewidth)
721 *ximages = (int)ceil((scale * imagewidth) / (pagewidth - overlap));
722 else
723 *ximages = 1;
724 *yimages = (int)ceil((scale * imageheight) / (splitheight - overlap)); /* Max vert pages needed */
725 }
726 else
727 {
728 if (pagewidth)
729 *ximages = (int)ceil((scale * imagewidth) / (pagewidth - overlap)); /* Max horz pages needed */
730 else
731 *ximages = 1;
732 *yimages = 1; /* Max vert pages needed */
733 }
734 }
735 else
736 {
737 if (splitwidth > 0) /* -W maxPageWidth */
738 {
739 if (imagewidth >splitwidth)
740 {
741 *ximages = (int)ceil((scale * imagewidth) / (splitwidth - overlap)); /* Max horz pages needed */
742 if (pageheight)
743 *yimages = (int)ceil((scale * imageheight) / (pageheight - overlap)); /* Max vert pages needed */
744 else
745 *yimages = 1;
746 }
747 else
748 {
749 *ximages = 1; /* Max vert pages needed */
750 if (pageheight)
751 *yimages = (int)ceil((scale * imageheight) / (pageheight - overlap)); /* Max vert pages needed */
752 else
753 *yimages = 1;
754 }
755 }
756 else
757 {
758 *ximages = 1;
759 *yimages = 1;
760 }
761 }
762 break;
763 case 90:
764 case 270: if (splitheight > 0) /* -H maxPageHeight */
765 {
766 if (imagewidth > splitheight) /* More than one vertical image segment */
767 {
768 *yimages = (int)ceil((scale * imagewidth) / (splitheight - overlap)); /* Max vert pages needed */
769 if (pagewidth)
770 *ximages = (int)ceil((scale * imageheight) / (pagewidth - overlap)); /* Max horz pages needed */
771 else
772 *ximages = 1;
773 }
774 else
775 {
776 *yimages = 1; /* Max vert pages needed */
777 if (pagewidth)
778 *ximages = (int)ceil((scale * imageheight) / (pagewidth - overlap)); /* Max horz pages needed */
779 else
780 *ximages = 1;
781 }
782 }
783 else
784 {
785 if (splitwidth > 0) /* -W maxPageWidth */
786 {
787 if (imageheight > splitwidth)
788 {
789 if (pageheight)
790 *yimages = (int)ceil((scale * imagewidth) / (pageheight - overlap)); /* Max vert pages needed */
791 else
792 *yimages = 1;
793 *ximages = (int)ceil((scale * imageheight) / (splitwidth - overlap)); /* Max horz pages needed */
794 }
795 else
796 {
797 if (pageheight)
798 *yimages = (int)ceil((scale * imagewidth) / (pageheight - overlap)); /* Max horz pages needed */
799 else
800 *yimages = 1;
801 *ximages = 1; /* Max vert pages needed */
802 }
803 }
804 else
805 {
806 *ximages = 1;
807 *yimages = 1;
808 }
809 }
810 break;
811 default: *ximages = 1;
812 *yimages = 1;
813 }
814 pages = (*ximages) * (*yimages);
815 return (pages);
816 }
817
818 /* New version of PlaceImage that handles only the translation and rotation
819 * for a single output page.
820 */
821 int exportMaskedImage(FILE *fp, double pagewidth, double pageheight,
822 double imagewidth, double imageheight,
823 int row, int column,
824 double left_offset, double bott_offset,
825 double scale, int center, int rotation)
826 {
827 double xtran = 0.0;
828 double ytran = 0.0;
829
830 double xscale = 1.0;
831 double yscale = 1.0;
832
833 double splitheight = 0; /* Requested Max Height in points */
834 double splitwidth = 0; /* Requested Max Width in points */
835 double overlap = 0; /* Repeated edge width in points */
836 double subimage_height = 0.0;
837
838 splitheight = maxPageHeight * PS_UNIT_SIZE;
839 splitwidth = maxPageWidth * PS_UNIT_SIZE;
840 overlap = splitOverlap * PS_UNIT_SIZE;
841 xscale = scale * imagewidth;
842 yscale = scale * imageheight;
843
844 if ((xscale < 0.0) || (yscale < 0.0))
845 {
846 TIFFError("exportMaskedImage", "Invalid parameters.");
847 return (-1);
848 }
849
850 /* If images are cropped to a vewport with -H or -W, the output pages are shifted to
851 * the top of each output page rather than the Postscript default lower edge.
852 */
853 switch (rotation)
854 {
855 case 0:
856 case 180: if (splitheight > 0) /* -H maxPageHeight */
857 {
858 if (splitheight < imageheight) /* More than one vertical image segments */
859 {
860 xtran = -1.0 * column * (pagewidth - overlap);
861 subimage_height = imageheight - ((splitheight - overlap) * row);
862 ytran = pageheight - subimage_height * (pageheight / splitheight);
863 }
864 else /* Only one page in vertical direction */
865 {
866 xtran = -1.0 * column * (pagewidth - overlap);
867 ytran = splitheight - imageheight;
868 }
869 }
870 else
871 {
872 if (splitwidth > 0) /* maxPageWidth */
873 {
874 if (splitwidth < imagewidth)
875 {
876 xtran = -1.0 * column * splitwidth;
877 ytran = -1.0 * row * (pageheight - overlap);
878 }
879 else /* Only one page in horizontal direction */
880 {
881 ytran = -1.0 * row * (pageheight - overlap);
882 xtran = 0;
883 }
884 }
885 else /* Simple case, no splitting */
886 {
887 ytran = pageheight - imageheight;
888 xtran = 0;
889 }
890 }
891 bott_offset += ytran / (center ? 2 : 1);
892 left_offset += xtran / (center ? 2 : 1);
893 break;
894 case 90:
895 case 270: if (splitheight > 0) /* -H maxPageHeight */
896 {
897 if (splitheight < imagewidth) /* More than one vertical image segments */
898 {
899 xtran = -1.0 * column * (pageheight - overlap);
900 /* Commented code places image at bottom of page instead of top.
901 ytran = -1.0 * row * splitheight;
902 */
903 if (row == 0)
904 ytran = -1.0 * (imagewidth - splitheight);
905 else
906 ytran = -1.0 * (imagewidth - (splitheight - overlap) * (row + 1));
907 }
908 else /* Only one page in vertical direction */
909 {
910 xtran = -1.0 * column * (pageheight - overlap);
911 ytran = splitheight - imagewidth;
912 }
913 }
914 else
915 {
916 if (splitwidth > 0) /* maxPageWidth */
917 {
918 if (splitwidth < imageheight)
919 {
920 xtran = -1.0 * column * splitwidth;
921 ytran = -1.0 * row * (pagewidth - overlap);
922 }
923 else /* Only one page in horizontal direction */
924 {
925 ytran = -1.0 * row * (pagewidth - overlap);
926 xtran = 0;
927 }
928 }
929 else /* Simple case, no splitting */
930 {
931 ytran = pageheight - imageheight;
932 xtran = 0; /* pagewidth - imagewidth; */
933 }
934 }
935 bott_offset += ytran / (center ? 2 : 1);
936 left_offset += xtran / (center ? 2 : 1);
937 break;
938 default: xtran = 0;
939 ytran = 0;
940 }
941
942 switch (rotation)
943 {
944 case 0: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
945 fprintf(fp, "%f %f scale\n", xscale, yscale);
946 break;
947 case 180: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
948 fprintf(fp, "%f %f scale\n1 1 translate 180 rotate\n", xscale, yscale);
949 break;
950 case 90: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
951 fprintf(fp, "%f %f scale\n1 0 translate 90 rotate\n", yscale, xscale);
952 break;
953 case 270: fprintf(fp, "%f %f translate\n", left_offset, bott_offset);
954 fprintf(fp, "%f %f scale\n0 1 translate 270 rotate\n", yscale, xscale);
955 break;
956 default: TIFFError ("exportMaskedImage", "Unsupported rotation angle %d. No rotation", rotation);
957 fprintf( fp, "%f %f scale\n", xscale, yscale);
958 break;
959 }
960
961 return (0);
962 }
963
964 /* Rotate an image without scaling or clipping */
965 int psRotateImage (FILE * fd, int rotation, double pswidth, double psheight,
966 double left_offset, double bottom_offset)
967 {
968 if ((left_offset != 0.0) || (bottom_offset != 0))
969 fprintf (fd, "%f %f translate\n", left_offset, bottom_offset);
970
971 /* Exchange width and height for 90/270 rotations */
972 switch (rotation)
973 {
974 case 0: fprintf (fd, "%f %f scale\n", pswidth, psheight);
975 break;
976 case 90: fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", psheight, pswidth);
977 break;
978 case 180: fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", pswidth, psheight);
979 break;
980 case 270: fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", psheight, pswidth);
981 break;
982 default: TIFFError ("psRotateImage", "Unsupported rotation %d.", rotation);
983 fprintf( fd, "%f %f scale\n", pswidth, psheight);
984 return (1);
985 }
986 return (0);
987 }
988
989 /* Scale and rotate an image to a single output page. */
990 int psScaleImage(FILE * fd, double scale, int rotation, int center,
991 double reqwidth, double reqheight, double pswidth, double psheight,
992 double left_offset, double bottom_offset)
993 {
994 double hcenter = 0.0, vcenter = 0.0;
995
996 /* Adjust offsets for centering */
997 if (center)
998 {
999 switch (rotation)
1000 {
1001 case 90: vcenter = (reqheight - pswidth * scale) / 2;
1002 hcenter = (reqwidth - psheight * scale) / 2;
1003 fprintf (fd, "%f %f translate\n", hcenter, vcenter);
1004 fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", psheight * scale, pswidth * scale);
1005 break;
1006 case 180: hcenter = (reqwidth - pswidth * scale) / 2;
1007 vcenter = (reqheight - psheight * scale) / 2;
1008 fprintf (fd, "%f %f translate\n", hcenter, vcenter);
1009 fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", pswidth * scale, psheight * scale);
1010 break;
1011 case 270: vcenter = (reqheight - pswidth * scale) / 2;
1012 hcenter = (reqwidth - psheight * scale) / 2;
1013 fprintf (fd, "%f %f translate\n", hcenter, vcenter);
1014 fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", psheight * scale, pswidth * scale);
1015 break;
1016 case 0:
1017 default: hcenter = (reqwidth - pswidth * scale) / 2;
1018 vcenter = (reqheight - psheight * scale) / 2;
1019 fprintf (fd, "%f %f translate\n", hcenter, vcenter);
1020 fprintf (fd, "%f %f scale\n", pswidth * scale, psheight * scale);
1021 break;
1022 }
1023 }
1024 else /* Not centered */
1025 {
1026 switch (rotation)
1027 {
1028 case 0: fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
1029 bottom_offset ? bottom_offset : reqheight - (psheight * scale));
1030 fprintf (fd, "%f %f scale\n", pswidth * scale, psheight * scale);
1031 break;
1032 case 90: fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
1033 bottom_offset ? bottom_offset : reqheight - (pswidth * scale));
1034 fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", psheight * scale, pswidth * scale);
1035 break;
1036 case 180: fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
1037 bottom_offset ? bottom_offset : reqheight - (psheight * scale));
1038 fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", pswidth * scale, psheight * scale);
1039 break;
1040 case 270: fprintf (fd, "%f %f translate\n", left_offset ? left_offset : 0.0,
1041 bottom_offset ? bottom_offset : reqheight - (pswidth * scale));
1042 fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", psheight * scale, pswidth * scale);
1043 break;
1044 default: TIFFError ("psScaleImage", "Unsupported rotation %d", rotation);
1045 fprintf (fd, "%f %f scale\n", pswidth * scale, psheight * scale);
1046 return (1);
1047 }
1048 }
1049
1050 return (0);
1051 }
1052
1053 /* This controls the visible portion of the page which is displayed.
1054 * N.B. Setting maxPageHeight no longer sets pageheight if not set explicitly
1055 */
1056 int psPageSize (FILE * fd, int rotation, double pgwidth, double pgheight,
1057 double reqwidth, double reqheight, double pswidth, double psheight)
1058 {
1059 double xscale = 1.0, yscale = 1.0, scale = 1.0;
1060 double splitheight;
1061 double splitwidth;
1062 double new_width;
1063 double new_height;
1064
1065 splitheight = maxPageHeight * PS_UNIT_SIZE;
1066 splitwidth = maxPageWidth * PS_UNIT_SIZE;
1067
1068 switch (rotation)
1069 {
1070 case 0:
1071 case 180: if ((splitheight > 0) || (splitwidth > 0))
1072 {
1073 if (pgwidth != 0 || pgheight != 0)
1074 {
1075 xscale = reqwidth / (splitwidth ? splitwidth : pswidth);
1076 yscale = reqheight / (splitheight ? splitheight : psheight);
1077 scale = (xscale < yscale) ? xscale : yscale;
1078 }
1079 new_width = splitwidth ? splitwidth : scale * pswidth;
1080 new_height = splitheight ? splitheight : scale * psheight;
1081 if (strlen(pageOrientation))
1082 fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
1083 else
1084 fprintf (fd, "%%%%PageOrientation: %s\n", (new_width > new_height) ? "Landscape" : "Portrait");
1085 fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)new_width, (long)new_height);
1086 fprintf (fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
1087 new_width, new_height);
1088 }
1089 else /* No viewport defined with -H or -W */
1090 {
1091 if ((pgwidth == 0) && (pgheight == 0)) /* Image not scaled */
1092 {
1093 if (strlen(pageOrientation))
1094 fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
1095 else
1096 fprintf (fd, "%%%%PageOrientation: %s\n", (pswidth > psheight) ? "Landscape" : "Portrait");
1097 fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)pswidth, (long)psheight);
1098 fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
1099 pswidth, psheight);
1100 }
1101 else /* Image scaled */
1102 {
1103 if (strlen(pageOrientation))
1104 fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
1105 else
1106 fprintf (fd, "%%%%PageOrientation: %s\n", (reqwidth > reqheight) ? "Landscape" : "Portrait");
1107 fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)reqwidth, (long)reqheight);
1108 fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
1109 reqwidth, reqheight);
1110 }
1111 }
1112 break;
1113 case 90:
1114 case 270: if ((splitheight > 0) || (splitwidth > 0))
1115 {
1116 if (pgwidth != 0 || pgheight != 0)
1117 {
1118 xscale = reqwidth / (splitwidth ? splitwidth : pswidth);
1119 yscale = reqheight / (splitheight ? splitheight : psheight);
1120 scale = (xscale < yscale) ? xscale : yscale;
1121 }
1122 new_width = splitwidth ? splitwidth : scale * psheight;
1123 new_height = splitheight ? splitheight : scale * pswidth;
1124
1125 if (strlen(pageOrientation))
1126 fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
1127 else
1128 fprintf (fd, "%%%%PageOrientation: %s\n", (new_width > new_height) ? "Landscape" : "Portrait");
1129 fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)new_width, (long)new_height);
1130 fprintf (fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
1131 new_width, new_height);
1132 }
1133 else
1134 {
1135 if ((pgwidth == 0) && (pgheight == 0)) /* Image not scaled */
1136 {
1137 if (strlen(pageOrientation))
1138 fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
1139 else
1140 fprintf (fd, "%%%%PageOrientation: %s\n", (psheight > pswidth) ? "Landscape" : "Portrait");
1141 fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)psheight, (long)pswidth);
1142 fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
1143 psheight, pswidth);
1144 }
1145 else /* Image scaled */
1146 {
1147 if (strlen(pageOrientation))
1148 fprintf (fd, "%%%%PageOrientation: %s\n", pageOrientation);
1149 else
1150 fprintf (fd, "%%%%PageOrientation: %s\n", (reqwidth > reqheight) ? "Landscape" : "Portrait");
1151 fprintf (fd, "%%%%PageBoundingBox: 0 0 %ld %ld\n", (long)reqwidth, (long)reqheight);
1152 fprintf(fd, "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n",
1153 reqwidth, reqheight);
1154 }
1155 }
1156 break;
1157 default: TIFFError ("psPageSize", "Invalid rotation %d", rotation);
1158 return (1);
1159 }
1160 fputs("<<\n /Policies <<\n /PageSize 3\n >>\n>> setpagedevice\n", fd);
1161
1162 return (0);
1163 } /* end psPageSize */
1164
1165 /* Mask an image as a series of pages, each only showing a section defined
1166 * by the maxPageHeight or maxPageWidth options.
1167 */
1168 int psMaskImage(FILE *fd, TIFF *tif, int rotation, int center,
1169 int *npages, double pixwidth, double pixheight,
1170 double left_margin, double bottom_margin,
1171 double pgwidth, double pgheight,
1172 double pswidth, double psheight, double scale)
1173 {
1174 int i, j;
1175 int ximages = 1, yimages = 1;
1176 int pages = *npages;
1177 double view_width = 0;
1178 double view_height = 0;
1179
1180 if (get_viewport (pgwidth, pgheight, pswidth, psheight, &view_width, &view_height, rotation))
1181 {
1182 TIFFError ("get_viewport", "Unable to set image viewport");
1183 return (-1);
1184 }
1185
1186 if (get_subimage_count(pgwidth, pgheight, pswidth, psheight,
1187 &ximages, &yimages, rotation, scale) < 1)
1188 {
1189 TIFFError("get_subimage_count", "Invalid image count: %d columns, %d rows", ximages, yimages);
1190 return (-1);
1191 }
1192
1193 for (i = 0; i < yimages; i++)
1194 {
1195 for (j = 0; j < ximages; j++)
1196 {
1197 pages++;
1198 *npages = pages;
1199 fprintf(fd, "%%%%Page: %d %d\n", pages, pages);
1200
1201 /* Write out the PageSize info for non EPS files */
1202 if (!generateEPSF && ( level2 || level3 ))
1203 {
1204 if (psPageSize(fd, rotation, pgwidth, pgheight,
1205 view_width, view_height, pswidth, psheight))
1206 return (-1);
1207 }
1208 fprintf(fd, "gsave\n");
1209 fprintf(fd, "100 dict begin\n");
1210 if (exportMaskedImage(fd, view_width, view_height, pswidth, psheight,
1211 i, j, left_margin, bottom_margin,
1212 scale, center, rotation))
1213 {
1214 TIFFError("exportMaskedImage", "Invalid image parameters.");
1215 return (-1);
1216 }
1217 PSpage(fd, tif, pixwidth, pixheight);
1218 fprintf(fd, "end\n");
1219 fprintf(fd, "grestore\n");
1220 fprintf(fd, "showpage\n");
1221 }
1222 }
1223
1224 return (pages);
1225 }
1226
1227 /* Compute scale factor and write out file header */
1228 int psStart(FILE *fd, int npages, int auto_rotate, int *rotation, double *scale,
1229 double ox, double oy, double pgwidth, double pgheight,
1230 double reqwidth, double reqheight, double pswidth, double psheight,
1231 double left_offset, double bottom_offset)
1232 {
1233 double maxsource = 0.0; /* Used for auto rotations */
1234 double maxtarget = 0.0;
1235 double xscale = 1.0, yscale = 1.0;
1236 double splitheight;
1237 double splitwidth;
1238 double view_width = 0.0, view_height = 0.0;
1239 double page_width = 0.0, page_height = 0.0;
1240
1241 /* Splitheight and splitwidth are in inches */
1242 splitheight = maxPageHeight * PS_UNIT_SIZE;
1243 splitwidth = maxPageWidth * PS_UNIT_SIZE;
1244
1245 page_width = pgwidth * PS_UNIT_SIZE;
1246 page_height = pgheight * PS_UNIT_SIZE;
1247
1248 /* If user has specified a page width and height and requested the
1249 * image to be auto-rotated to fit on that media, we match the
1250 * longest dimension of the image to the longest dimension of the
1251 * target media but we have to ignore auto rotate if user specified
1252 * maxPageHeight since this makes life way too complicated. */
1253 if (auto_rotate)
1254 {
1255 if ((splitheight != 0) || (splitwidth != 0))
1256 {
1257 TIFFError ("psStart", "Auto-rotate is incompatible with page splitting ");
1258 return (1);
1259 }
1260
1261 /* Find longest edges in image and output media */
1262 maxsource = (pswidth >= psheight) ? pswidth : psheight;
1263 maxtarget = (reqwidth >= reqheight) ? reqwidth : reqheight;
1264
1265 if (((maxsource == pswidth) && (maxtarget != reqwidth)) ||
1266 ((maxsource == psheight) && (maxtarget != reqheight)))
1267 { /* optimal orientaion does not match input orientation */
1268 *rotation = 90;
1269 xscale = (reqwidth - left_offset)/psheight;
1270 yscale = (reqheight - bottom_offset)/pswidth;
1271 }
1272 else /* optimal orientaion matches input orientation */
1273 {
1274 xscale = (reqwidth - left_offset)/pswidth;
1275 yscale = (reqheight - bottom_offset)/psheight;
1276 }
1277 *scale = (xscale < yscale) ? xscale : yscale;
1278
1279 /* Do not scale image beyound original size */
1280 if (*scale > 1.0)
1281 *scale = 1.0;
1282
1283 /* Set the size of the displayed image to requested page size
1284 * and optimal orientation.
1285 */
1286 if (!npages)
1287 PSHead(fd, reqwidth, reqheight, ox, oy);
1288
1289 return (0);
1290 }
1291
1292 /* N.B. If pgwidth or pgheight are set from maxPageHeight/Width,
1293 * we have a problem with the tests below under splitheight.
1294 */
1295
1296 switch (*rotation) /* Auto rotate has NOT been specified */
1297 {
1298 case 0:
1299 case 180: if ((splitheight != 0) || (splitwidth != 0))
1300 { /* Viewport clipped to maxPageHeight or maxPageWidth */
1301 if ((page_width != 0) || (page_height != 0)) /* Image scaled */
1302 {
1303 xscale = (reqwidth - left_offset) / (page_width ? page_width : pswidth);
1304 yscale = (reqheight - bottom_offset) / (page_height ? page_height : psheight);
1305 *scale = (xscale < yscale) ? xscale : yscale;
1306 /*
1307 if (*scale > 1.0)
1308 *scale = 1.0;
1309 */
1310 }
1311 else /* Image clipped but not scaled */
1312 *scale = 1.0;
1313
1314 view_width = splitwidth ? splitwidth : *scale * pswidth;
1315 view_height = splitheight ? splitheight: *scale * psheight;
1316 }
1317 else /* Viewport not clipped to maxPageHeight or maxPageWidth */
1318 {
1319 if ((page_width != 0) || (page_height != 0))
1320 { /* Image scaled */
1321 xscale = (reqwidth - left_offset) / pswidth;
1322 yscale = (reqheight - bottom_offset) / psheight;
1323
1324 view_width = reqwidth;
1325 view_height = reqheight;
1326 }
1327 else
1328 { /* Image not scaled */
1329 xscale = (pswidth - left_offset)/pswidth;
1330 yscale = (psheight - bottom_offset)/psheight;
1331
1332 view_width = pswidth;
1333 view_height = psheight;
1334 }
1335 }
1336 break;
1337 case 90:
1338 case 270: if ((splitheight != 0) || (splitwidth != 0))
1339 { /* Viewport clipped to maxPageHeight or maxPageWidth */
1340 if ((page_width != 0) || (page_height != 0)) /* Image scaled */
1341 {
1342 xscale = (reqwidth - left_offset)/ psheight;
1343 yscale = (reqheight - bottom_offset)/ pswidth;
1344 *scale = (xscale < yscale) ? xscale : yscale;
1345 /*
1346 if (*scale > 1.0)
1347 *scale = 1.0;
1348 */
1349 }
1350 else /* Image clipped but not scaled */
1351 *scale = 1.0;
1352 view_width = splitwidth ? splitwidth : *scale * psheight;
1353 view_height = splitheight ? splitheight : *scale * pswidth;
1354 }
1355 else /* Viewport not clipped to maxPageHeight or maxPageWidth */
1356 {
1357 if ((page_width != 0) || (page_height != 0)) /* Image scaled */
1358 {
1359 xscale = (reqwidth - left_offset) / psheight;
1360 yscale = (reqheight - bottom_offset) / pswidth;
1361
1362 view_width = reqwidth;
1363 view_height = reqheight;
1364 }
1365 else
1366 {
1367 xscale = (pswidth - left_offset)/ psheight;
1368 yscale = (psheight - bottom_offset)/ pswidth;
1369
1370 view_width = psheight;
1371 view_height = pswidth;
1372 }
1373 }
1374 break;
1375 default: TIFFError ("psPageSize", "Invalid rotation %d", *rotation);
1376 return (1);
1377 }
1378
1379 if (!npages)
1380 PSHead(fd, (page_width ? page_width : view_width), (page_height ? page_height : view_height), ox, oy);
1381
1382 *scale = (xscale < yscale) ? xscale : yscale;
1383 if (*scale > 1.0)
1384 *scale = 1.0;
1385
1386 return (0);
1387 }
1388
1389 int get_viewport (double pgwidth, double pgheight, double pswidth, double psheight,
1390 double *view_width, double *view_height, int rotation)
1391 {
1392 /* Only one of maxPageHeight or maxPageWidth can be specified */
1393 if (maxPageHeight != 0) /* Clip the viewport to maxPageHeight on each page */
1394 {
1395 *view_height = maxPageHeight * PS_UNIT_SIZE;
1396 /*
1397 * if (res_unit == RESUNIT_CENTIMETER)
1398 * *view_height /= 2.54F;
1399 */
1400 }
1401 else
1402 {
1403 if (pgheight != 0) /* User has set PageHeight with -h flag */
1404 {
1405 *view_height = pgheight * PS_UNIT_SIZE; /* Postscript size for Page Height in inches */
1406 /* if (res_unit == RESUNIT_CENTIMETER)
1407 * *view_height /= 2.54F;
1408 */
1409 }
1410 else /* If no width or height are specified, use the original size from image */
1411 switch (rotation)
1412 {
1413 default:
1414 case 0:
1415 case 180: *view_height = psheight;
1416 break;
1417 case 90:
1418 case 270: *view_height = pswidth;
1419 break;
1420 }
1421 }
1422
1423 if (maxPageWidth != 0) /* Clip the viewport to maxPageWidth on each page */
1424 {
1425 *view_width = maxPageWidth * PS_UNIT_SIZE;
1426 /* if (res_unit == RESUNIT_CENTIMETER)
1427 * *view_width /= 2.54F;
1428 */
1429 }
1430 else
1431 {
1432 if (pgwidth != 0) /* User has set PageWidth with -w flag */
1433 {
1434 *view_width = pgwidth * PS_UNIT_SIZE; /* Postscript size for Page Width in inches */
1435 /* if (res_unit == RESUNIT_CENTIMETER)
1436 * *view_width /= 2.54F;
1437 */
1438 }
1439 else /* If no width or height are specified, use the original size from image */
1440 switch (rotation)
1441 {
1442 default:
1443 case 0:
1444 case 180: *view_width = pswidth;
1445 break;
1446 case 90:
1447 case 270: *view_width = psheight; /* (*view_height / psheight) * psheight; */
1448 break;
1449 }
1450 }
1451
1452 return (0);
1453 }
1454
1455 /* pgwidth and pgheight specify page width and height in inches from -h and -w flags
1456 * lm and bm are the LeftMargin and BottomMargin in inches
1457 * center causes the image to be centered on the page if the paper size is
1458 * larger than the image size
1459 * returns the sequence number of the page processed or -1 on error
1460 */
1461
1462 int TIFF2PS(FILE* fd, TIFF* tif, double pgwidth, double pgheight, double lm, double bm, int center)
1463 {
1464 uint32 pixwidth = 0, pixheight = 0; /* Image width and height in pixels */
1465 double ox = 0.0, oy = 0.0; /* Offset from current Postscript origin */
1466 double pswidth, psheight; /* Original raw image width and height in points */
1467 double view_width, view_height; /* Viewport width and height in points */
1468 double scale = 1.0;
1469 double left_offset = lm * PS_UNIT_SIZE;
1470 double bottom_offset = bm * PS_UNIT_SIZE;
1471 uint32 subfiletype;
1472 uint16* sampleinfo;
1473 static int npages = 0;
1474
1475 if (!TIFFGetField(tif, TIFFTAG_XPOSITION, &ox))
1476 ox = 0;
1477 if (!TIFFGetField(tif, TIFFTAG_YPOSITION, &oy))
1478 oy = 0;
1479
1480 /* Consolidated all the tag information into one code segment, Richard Nolde */
1481 do {
1482 tf_numberstrips = TIFFNumberOfStrips(tif);
1483 TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &tf_rowsperstrip);
1484 TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bitspersample);
1485 TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
1486 TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planarconfiguration);
1487 TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression);
1488 TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, &extrasamples, &sampleinfo);
1489 alpha = (extrasamples == 1 && sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA);
1490 if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric))
1491 {
1492 switch (samplesperpixel - extrasamples)
1493 {
1494 case 1: if (isCCITTCompression(tif))
1495 photometric = PHOTOMETRIC_MINISWHITE;
1496 else
1497 photometric = PHOTOMETRIC_MINISBLACK;
1498 break;
1499 case 3: photometric = PHOTOMETRIC_RGB;
1500 break;
1501 case 4: photometric = PHOTOMETRIC_SEPARATED;
1502 break;
1503 }
1504 }
1505
1506 /* Read image tags for width and height in pixels pixwidth, pixheight,
1507 * and convert to points pswidth, psheight
1508 */
1509 setupPageState(tif, &pixwidth, &pixheight, &pswidth, &psheight);
1510 view_width = pswidth;
1511 view_height = psheight;
1512
1513 if (get_viewport (pgwidth, pgheight, pswidth, psheight, &view_width, &view_height, rotation))
1514 {
1515 TIFFError("get_viewport", "Unable to set image viewport");
1516 return (1);
1517 }
1518
1519 /* Write the Postscript file header with Bounding Box and Page Size definitions */
1520 if (psStart(fd, npages, auto_rotate, &rotation, &scale, ox, oy,
1521 pgwidth, pgheight, view_width, view_height, pswidth, psheight,
1522 left_offset, bottom_offset))
1523 return (-1);
1524
1525 if (checkImage(tif)) /* Aborts if unsupported image parameters */
1526 {
1527 tf_bytesperrow = TIFFScanlineSize(tif);
1528
1529 /* Set viewport clipping and scaling options */
1530 if ((maxPageHeight) || (maxPageWidth) || (pgwidth != 0) || (pgheight != 0))
1531 {
1532 if ((maxPageHeight) || (maxPageWidth)) /* used -H or -W option */
1533 {
1534 if (psMaskImage(fd, tif, rotation, center, &npages, pixwidth, pixheight,
1535 left_offset, bottom_offset, pgwidth, pgheight,
1536 pswidth, psheight, scale) < 0)
1537 return (-1);
1538 }
1539 else /* N.B. Setting maxPageHeight no longer sets pgheight */
1540 {
1541 if (pgwidth != 0 || pgheight != 0)
1542 {
1543 /* User did not specify a maxium page height or width using -H or -W flag
1544 * but did use -h or -w flag to scale to a specific size page.
1545 */
1546 npages++;
1547 fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
1548
1549 if (!generateEPSF && ( level2 || level3 ))
1550 {
1551 /* Write out the PageSize info for non EPS files */
1552 if (psPageSize(fd, rotation, pgwidth, pgheight,
1553 view_width, view_height, pswidth, psheight))
1554 return (-1);
1555 }
1556 fprintf(fd, "gsave\n");
1557 fprintf(fd, "100 dict begin\n");
1558 if (psScaleImage(fd, scale, rotation, center, view_width, view_height,
1559 pswidth, psheight, left_offset, bottom_offset))
1560 return (-1);
1561
1562 PSpage(fd, tif, pixwidth, pixheight);
1563 fprintf(fd, "end\n");
1564 fprintf(fd, "grestore\n");
1565 fprintf(fd, "showpage\n");
1566 }
1567 }
1568 }
1569 else /* Simple rotation: user did not use -H, -W, -h or -w */
1570 {
1571 npages++;
1572 fprintf(fd, "%%%%Page: %d %d\n", npages, npages);
1573
1574 if (!generateEPSF && ( level2 || level3 ))
1575 {
1576 /* Write out the PageSize info for non EPS files */
1577 if (psPageSize(fd, rotation, pgwidth, pgheight,
1578 view_width, view_height, pswidth, psheight))
1579 return (-1);
1580 }
1581 fprintf(fd, "gsave\n");
1582 fprintf(fd, "100 dict begin\n");
1583 if (psRotateImage(fd, rotation, pswidth, psheight, left_offset, bottom_offset))
1584 return (-1);
1585
1586 PSpage(fd, tif, pixwidth, pixheight);
1587 fprintf(fd, "end\n");
1588 fprintf(fd, "grestore\n");
1589 fprintf(fd, "showpage\n");
1590 }
1591 }
1592 if (generateEPSF)
1593 break;
1594 TIFFGetFieldDefaulted(tif, TIFFTAG_SUBFILETYPE, &subfiletype);
1595 } while (((subfiletype & FILETYPE_PAGE) || printAll) && TIFFReadDirectory(tif));
1596
1597 return(npages);
1598 }
1599
1600 static char DuplexPreamble[] = "\
1601 %%BeginFeature: *Duplex True\n\
1602 systemdict begin\n\
1603 /languagelevel where { pop languagelevel } { 1 } ifelse\n\
1604 2 ge { 1 dict dup /Duplex true put setpagedevice }\n\
1605 { statusdict /setduplex known { statusdict begin setduplex true end } if\n\
1606 } ifelse\n\
1607 end\n\
1608 %%EndFeature\n\
1609 ";
1610
1611 static char TumblePreamble[] = "\
1612 %%BeginFeature: *Tumble True\n\
1613 systemdict begin\n\
1614 /languagelevel where { pop languagelevel } { 1 } ifelse\n\
1615 2 ge { 1 dict dup /Tumble true put setpagedevice }\n\
1616 { statusdict /settumble known { statusdict begin true settumble end } if\n\
1617 } ifelse\n\
1618 end\n\
1619 %%EndFeature\n\
1620 ";
1621
1622 static char AvoidDeadZonePreamble[] = "\
1623 gsave newpath clippath pathbbox grestore\n\
1624 4 2 roll 2 copy translate\n\
1625 exch 3 1 roll sub 3 1 roll sub exch\n\
1626 currentpagedevice /PageSize get aload pop\n\
1627 exch 3 1 roll div 3 1 roll div abs exch abs\n\
1628 2 copy gt { exch } if pop\n\
1629 dup 1 lt { dup scale } { pop } ifelse\n\
1630 ";
1631
1632 void
1633 PSHead(FILE *fd, double pagewidth, double pageheight, double xoff, double yoff)
1634 {
1635 time_t t;
1636
1637 t = time(0);
1638 fprintf(fd, "%%!PS-Adobe-3.0%s\n", generateEPSF ? " EPSF-3.0" : "");
1639 fprintf(fd, "%%%%Creator: %s\n", creator ? creator : "tiff2ps");
1640 fprintf(fd, "%%%%Title: %s\n", title ? title : filename);
1641 fprintf(fd, "%%%%CreationDate: %s", ctime(&t));
1642 fprintf(fd, "%%%%DocumentData: Clean7Bit\n");
1643 /* NB: should use PageBoundingBox for each page instead of BoundingBox *
1644 * PageBoundingBox DSC added in PSPageSize function, R Nolde 09-01-2010
1645 */
1646 fprintf(fd, "%%%%Origin: %ld %ld\n", (long) xoff, (long) yoff);
1647 fprintf(fd, "%%%%BoundingBox: 0 0 %ld %ld\n",
1648 (long) ceil(pagewidth), (long) ceil(pageheight));
1649
1650 fprintf(fd, "%%%%LanguageLevel: %d\n", (level3 ? 3 : (level2 ? 2 : 1)));
1651 if (generateEPSF == TRUE)
1652 fprintf(fd, "%%%%Pages: 1 1\n");
1653 else
1654 fprintf(fd, "%%%%Pages: (atend)\n");
1655 fprintf(fd, "%%%%EndComments\n");
1656 if (generateEPSF == FALSE)
1657 {
1658 fprintf(fd, "%%%%BeginSetup\n");
1659 if (PSduplex)
1660 fprintf(fd, "%s", DuplexPreamble);
1661 if (PStumble)
1662 fprintf(fd, "%s", TumblePreamble);
1663 if (PSavoiddeadzone && (level2 || level3))
1664 fprintf(fd, "%s", AvoidDeadZonePreamble);
1665 fprintf(fd, "%%%%EndSetup\n");
1666 }
1667 }
1668
1669 void
1670 PSTail(FILE *fd, int npages)
1671 {
1672 fprintf(fd, "%%%%Trailer\n");
1673 if (generateEPSF == FALSE)
1674 fprintf(fd, "%%%%Pages: %d\n", npages);
1675 fprintf(fd, "%%%%EOF\n");
1676 }
1677
1678 static int
1679 checkcmap(TIFF* tif, int n, uint16* r, uint16* g, uint16* b)
1680 {
1681 (void) tif;
1682 while (n-- > 0)
1683 if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
1684 return (16);
1685 TIFFWarning(filename, "Assuming 8-bit colormap");
1686 return (8);
1687 }
1688
1689 static void
1690 PS_Lvl2colorspace(FILE* fd, TIFF* tif)
1691 {
1692 uint16 *rmap, *gmap, *bmap;
1693 int i, num_colors;
1694 const char * colorspace_p;
1695
1696 switch ( photometric )
1697 {
1698 case PHOTOMETRIC_SEPARATED:
1699 colorspace_p = "CMYK";
1700 break;
1701
1702 case PHOTOMETRIC_RGB:
1703 colorspace_p = "RGB";
1704 break;
1705
1706 default:
1707 colorspace_p = "Gray";
1708 }
1709
1710 /*
1711 * Set up PostScript Level 2 colorspace according to
1712 * section 4.8 in the PostScript refenence manual.
1713 */
1714 fputs("% PostScript Level 2 only.\n", fd);
1715 if (photometric != PHOTOMETRIC_PALETTE) {
1716 if (photometric == PHOTOMETRIC_YCBCR) {
1717 /* MORE CODE HERE */
1718 }
1719 fprintf(fd, "/Device%s setcolorspace\n", colorspace_p );
1720 return;
1721 }
1722
1723 /*
1724 * Set up an indexed/palette colorspace
1725 */
1726 num_colors = (1 << bitspersample);
1727 if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
1728 TIFFError(filename,
1729 "Palette image w/o \"Colormap\" tag");
1730 return;
1731 }
1732 if (checkcmap(tif, num_colors, rmap, gmap, bmap) == 16) {
1733 /*
1734 * Convert colormap to 8-bits values.
1735 */
1736 #define CVT(x) (((x) * 255) / ((1L<<16)-1))
1737 for (i = 0; i < num_colors; i++) {
1738 rmap[i] = CVT(rmap[i]);
1739 gmap[i] = CVT(gmap[i]);
1740 bmap[i] = CVT(bmap[i]);
1741 }
1742 #undef CVT
1743 }
1744 fprintf(fd, "[ /Indexed /DeviceRGB %d", num_colors - 1);
1745 if (ascii85) {
1746 Ascii85Init();
1747 fputs("\n<~", fd);
1748 ascii85breaklen -= 2;
1749 } else
1750 fputs(" <", fd);
1751 for (i = 0; i < num_colors; i++) {
1752 if (ascii85) {
1753 Ascii85Put((unsigned char)rmap[i], fd);
1754 Ascii85Put((unsigned char)gmap[i], fd);
1755 Ascii85Put((unsigned char)bmap[i], fd);
1756 } else {
1757 fputs((i % 8) ? " " : "\n ", fd);
1758 fprintf(fd, "%02x%02x%02x",
1759 rmap[i], gmap[i], bmap[i]);
1760 }
1761 }
1762 if (ascii85)
1763 Ascii85Flush(fd);
1764 else
1765 fputs(">\n", fd);
1766 fputs("] setcolorspace\n", fd);
1767 }
1768
1769 static int
1770 PS_Lvl2ImageDict(FILE* fd, TIFF* tif, uint32 w, uint32 h)
1771 {
1772 int use_rawdata;
1773 uint32 tile_width, tile_height;
1774 uint16 predictor, minsamplevalue, maxsamplevalue;
1775 int repeat_count;
1776 char im_h[64], im_x[64], im_y[64];
1777 char * imageOp = "image";
1778
1779 if ( useImagemask && (bitspersample == 1) )
1780 imageOp = "imagemask";
1781
1782 (void)strcpy(im_x, "0");
1783 (void)sprintf(im_y, "%lu", (long) h);
1784 (void)sprintf(im_h, "%lu", (long) h);
1785 tile_width = w;
1786 tile_height = h;
1787 if (TIFFIsTiled(tif)) {
1788 repeat_count = TIFFNumberOfTiles(tif);
1789 TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width);
1790 TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height);
1791 if (tile_width > w || tile_height > h ||
1792 (w % tile_width) != 0 || (h % tile_height != 0)) {
1793 /*
1794 * The tiles does not fit image width and height.
1795 * Set up a clip rectangle for the image unit square.
1796 */
1797 fputs("0 0 1 1 rectclip\n", fd);
1798 }
1799 if (tile_width < w) {
1800 fputs("/im_x 0 def\n", fd);
1801 (void)strcpy(im_x, "im_x neg");
1802 }
1803 if (tile_height < h) {
1804 fputs("/im_y 0 def\n", fd);
1805 (void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
1806 }
1807 } else {
1808 repeat_count = tf_numberstrips;
1809 tile_height = tf_rowsperstrip;
1810 if (tile_height > h)
1811 tile_height = h;
1812 if (repeat_count > 1) {
1813 fputs("/im_y 0 def\n", fd);
1814 fprintf(fd, "/im_h %lu def\n",
1815 (unsigned long) tile_height);
1816 (void)strcpy(im_h, "im_h");
1817 (void)sprintf(im_y, "%lu im_y sub", (unsigned long) h);
1818 }
1819 }
1820
1821 /*
1822 * Output start of exec block
1823 */
1824 fputs("{ % exec\n", fd);
1825
1826 if (repeat_count > 1)
1827 fprintf(fd, "%d { %% repeat\n", repeat_count);
1828
1829 /*
1830 * Output filter options and image dictionary.
1831 */
1832 if (ascii85)
1833 fputs(" /im_stream currentfile /ASCII85Decode filter def\n",
1834 fd);
1835 fputs(" <<\n", fd);
1836 fputs(" /ImageType 1\n", fd);
1837 fprintf(fd, " /Width %lu\n", (unsigned long) tile_width);
1838 /*
1839 * Workaround for some software that may crash when last strip
1840 * of image contains fewer number of scanlines than specified
1841 * by the `/Height' variable. So for stripped images with multiple
1842 * strips we will set `/Height' as `im_h', because one is
1843 * recalculated for each strip - including the (smaller) final strip.
1844 * For tiled images and images with only one strip `/Height' will
1845 * contain number of scanlines in tile (or image height in case of
1846 * one-stripped image).
1847 */
1848 if (TIFFIsTiled(tif) || tf_numberstrips == 1)
1849 fprintf(fd, " /Height %lu\n", (unsigned long) tile_height);
1850 else
1851 fprintf(fd, " /Height im_h\n");
1852
1853 if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1)
1854 fputs(" /MultipleDataSources true\n", fd);
1855 fprintf(fd, " /ImageMatrix [ %lu 0 0 %ld %s %s ]\n",
1856 (unsigned long) w, - (long)h, im_x, im_y);
1857 fprintf(fd, " /BitsPerComponent %d\n", bitspersample);
1858 fprintf(fd, " /Interpolate %s\n", interpolate ? "true" : "false");
1859
1860 switch (samplesperpixel - extrasamples) {
1861 case 1:
1862 switch (photometric) {
1863 case PHOTOMETRIC_MINISBLACK:
1864 fputs(" /Decode [0 1]\n", fd);
1865 break;
1866 case PHOTOMETRIC_MINISWHITE:
1867 switch (compression) {
1868 case COMPRESSION_CCITTRLE:
1869 case COMPRESSION_CCITTRLEW:
1870 case COMPRESSION_CCITTFAX3:
1871 case COMPRESSION_CCITTFAX4:
1872 /*
1873 * Manage inverting with /Blackis1 flag
1874 * since there migth be uncompressed parts
1875 */
1876 fputs(" /Decode [0 1]\n", fd);
1877 break;
1878 default:
1879 /*
1880 * ERROR...
1881 */
1882 fputs(" /Decode [1 0]\n", fd);
1883 break;
1884 }
1885 break;
1886 case PHOTOMETRIC_PALETTE:
1887 TIFFGetFieldDefaulted(tif, TIFFTAG_MINSAMPLEVALUE,
1888 &minsamplevalue);
1889 TIFFGetFieldDefaulted(tif, TIFFTAG_MAXSAMPLEVALUE,
1890 &maxsamplevalue);
1891 fprintf(fd, " /Decode [%u %u]\n",
1892 minsamplevalue, maxsamplevalue);
1893 break;
1894 default:
1895 /*
1896 * ERROR ?
1897 */
1898 fputs(" /Decode [0 1]\n", fd);
1899 break;
1900 }
1901 break;
1902 case 3:
1903 switch (photometric) {
1904 case PHOTOMETRIC_RGB:
1905 fputs(" /Decode [0 1 0 1 0 1]\n", fd);
1906 break;
1907 case PHOTOMETRIC_MINISWHITE:
1908 case PHOTOMETRIC_MINISBLACK:
1909 default:
1910 /*
1911 * ERROR??
1912 */
1913 fputs(" /Decode [0 1 0 1 0 1]\n", fd);
1914 break;
1915 }
1916 break;
1917 case 4:
1918 /*
1919 * ERROR??
1920 */
1921 fputs(" /Decode [0 1 0 1 0 1 0 1]\n", fd);
1922 break;
1923 }
1924 fputs(" /DataSource", fd);
1925 if (planarconfiguration == PLANARCONFIG_SEPARATE &&
1926 samplesperpixel > 1)
1927 fputs(" [", fd);
1928 if (ascii85)
1929 fputs(" im_stream", fd);
1930 else
1931 fputs(" currentfile /ASCIIHexDecode filter", fd);
1932
1933 use_rawdata = TRUE;
1934 switch (compression) {
1935 case COMPRESSION_NONE: /* 1: uncompressed */
1936 break;
1937 case COMPRESSION_CCITTRLE: /* 2: CCITT modified Huffman RLE */
1938 case COMPRESSION_CCITTRLEW: /* 32771: #1 w/ word alignment */
1939 case COMPRESSION_CCITTFAX3: /* 3: CCITT Group 3 fax encoding */
1940 case COMPRESSION_CCITTFAX4: /* 4: CCITT Group 4 fax encoding */
1941 fputs("\n\t<<\n", fd);
1942 if (compression == COMPRESSION_CCITTFAX3) {
1943 uint32 g3_options;
1944
1945 fputs("\t /EndOfLine true\n", fd);
1946 fputs("\t /EndOfBlock false\n", fd);
1947 if (!TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS,
1948 &g3_options))
1949 g3_options = 0;
1950 if (g3_options & GROUP3OPT_2DENCODING)
1951 fprintf(fd, "\t /K %s\n", im_h);
1952 if (g3_options & GROUP3OPT_UNCOMPRESSED)
1953 fputs("\t /Uncompressed true\n", fd);
1954 if (g3_options & GROUP3OPT_FILLBITS)
1955 fputs("\t /EncodedByteAlign true\n", fd);
1956 }
1957 if (compression == COMPRESSION_CCITTFAX4) {
1958 uint32 g4_options;
1959
1960 fputs("\t /K -1\n", fd);
1961 TIFFGetFieldDefaulted(tif, TIFFTAG_GROUP4OPTIONS,
1962 &g4_options);
1963 if (g4_options & GROUP4OPT_UNCOMPRESSED)
1964 fputs("\t /Uncompressed true\n", fd);
1965 }
1966 if (!(tile_width == w && w == 1728U))
1967 fprintf(fd, "\t /Columns %lu\n",
1968 (unsigned long) tile_width);
1969 fprintf(fd, "\t /Rows %s\n", im_h);
1970 if (compression == COMPRESSION_CCITTRLE ||
1971 compression == COMPRESSION_CCITTRLEW) {
1972 fputs("\t /EncodedByteAlign true\n", fd);
1973 fputs("\t /EndOfBlock false\n", fd);
1974 }
1975 if (photometric == PHOTOMETRIC_MINISBLACK)
1976 fputs("\t /BlackIs1 true\n", fd);
1977 fprintf(fd, "\t>> /CCITTFaxDecode filter");
1978 break;
1979 case COMPRESSION_LZW: /* 5: Lempel-Ziv & Welch */
1980 TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
1981 if (predictor == 2) {
1982 fputs("\n\t<<\n", fd);
1983 fprintf(fd, "\t /Predictor %u\n", predictor);
1984 fprintf(fd, "\t /Columns %lu\n",
1985 (unsigned long) tile_width);
1986 fprintf(fd, "\t /Colors %u\n", samplesperpixel);
1987 fprintf(fd, "\t /BitsPerComponent %u\n",
1988 bitspersample);
1989 fputs("\t>>", fd);
1990 }
1991 fputs(" /LZWDecode filter", fd);
1992 break;
1993 case COMPRESSION_DEFLATE: /* 5: ZIP */
1994 case COMPRESSION_ADOBE_DEFLATE:
1995 if ( level3 ) {
1996 TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor);
1997 if (predictor > 1) {
1998 fprintf(fd, "\t %% PostScript Level 3 only.");
1999 fputs("\n\t<<\n", fd);
2000 fprintf(fd, "\t /Predictor %u\n", predictor);
2001 fprintf(fd, "\t /Columns %lu\n",
2002 (unsigned long) tile_width);
2003 fprintf(fd, "\t /Colors %u\n", samplesperpixel);
2004 fprintf(fd, "\t /BitsPerComponent %u\n",
2005 bitspersample);
2006 fputs("\t>>", fd);
2007 }
2008 fputs(" /FlateDecode filter", fd);
2009 } else {
2010 use_rawdata = FALSE ;
2011 }
2012 break;
2013 case COMPRESSION_PACKBITS: /* 32773: Macintosh RLE */
2014 fputs(" /RunLengthDecode filter", fd);
2015 use_rawdata = TRUE;
2016 break;
2017 case COMPRESSION_OJPEG: /* 6: !6.0 JPEG */
2018 case COMPRESSION_JPEG: /* 7: %JPEG DCT compression */
2019 #ifdef notdef
2020 /*
2021 * Code not tested yet
2022 */
2023 fputs(" /DCTDecode filter", fd);
2024 use_rawdata = TRUE;
2025 #else
2026 use_rawdata = FALSE;
2027 #endif
2028 break;
2029 case COMPRESSION_NEXT: /* 32766: NeXT 2-bit RLE */
2030 case COMPRESSION_THUNDERSCAN: /* 32809: ThunderScan RLE */
2031 case COMPRESSION_PIXARFILM: /* 32908: Pixar companded 10bit LZW */
2032 case COMPRESSION_JBIG: /* 34661: ISO JBIG */
2033 use_rawdata = FALSE;
2034 break;
2035 case COMPRESSION_SGILOG: /* 34676: SGI LogL or LogLuv */
2036 case COMPRESSION_SGILOG24: /* 34677: SGI 24-bit LogLuv */
2037 use_rawdata = FALSE;
2038 break;
2039 default:
2040 /*
2041 * ERROR...
2042 */
2043 use_rawdata = FALSE;
2044 break;
2045 }
2046 if (planarconfiguration == PLANARCONFIG_SEPARATE &&
2047 samplesperpixel > 1) {
2048 uint16 i;
2049
2050 /*
2051 * NOTE: This code does not work yet...
2052 */
2053 for (i = 1; i < samplesperpixel; i++)
2054 fputs(" dup", fd);
2055 fputs(" ]", fd);
2056 }
2057
2058 fprintf( fd, "\n >> %s\n", imageOp );
2059 if (ascii85)
2060 fputs(" im_stream status { im_stream flushfile } if\n", fd);
2061 if (repeat_count > 1) {
2062 if (tile_width < w) {
2063 fprintf(fd, " /im_x im_x %lu add def\n",
2064 (unsigned long) tile_width);
2065 if (tile_height < h) {
2066 fprintf(fd, " im_x %lu ge {\n",
2067 (unsigned long) w);
2068 fputs(" /im_x 0 def\n", fd);
2069 fprintf(fd, " /im_y im_y %lu add def\n",
2070 (unsigned long) tile_height);
2071 fputs(" } if\n", fd);
2072 }
2073 }
2074 if (tile_height < h) {
2075 if (tile_width >= w) {
2076 fprintf(fd, " /im_y im_y %lu add def\n",
2077 (unsigned long) tile_height);
2078 if (!TIFFIsTiled(tif)) {
2079 fprintf(fd, " /im_h %lu im_y sub",
2080 (unsigned long) h);
2081 fprintf(fd, " dup %lu gt { pop",
2082 (unsigned long) tile_height);
2083 fprintf(fd, " %lu } if def\n",
2084 (unsigned long) tile_height);
2085 }
2086 }
2087 }
2088 fputs("} repeat\n", fd);
2089 }
2090 /*
2091 * End of exec function
2092 */
2093 fputs("}\n", fd);
2094
2095 return(use_rawdata);
2096 }
2097
2098 /* Flip the byte order of buffers with 16 bit samples */
2099 static void
2100 PS_FlipBytes(unsigned char* buf, tsize_t count)
2101 {
2102 int i;
2103 unsigned char temp;
2104
2105 if (count <= 0 || bitspersample <= 8) {
2106 return;
2107 }
2108
2109 count--;
2110
2111 for (i = 0; i < count; i += 2) {
2112 temp = buf[i];
2113 buf[i] = buf[i + 1];
2114 buf[i + 1] = temp;
2115 }
2116 }
2117
2118 #define MAXLINE 36
2119
2120 int
2121 PS_Lvl2page(FILE* fd, TIFF* tif, uint32 w, uint32 h)
2122 {
2123 uint16 fillorder;
2124 int use_rawdata, tiled_image, breaklen = MAXLINE;
2125 uint32 chunk_no, num_chunks;
2126 uint64 *bc;
2127 unsigned char *buf_data, *cp;
2128 tsize_t chunk_size, byte_count;
2129
2130 #if defined( EXP_ASCII85ENCODER )
2131 tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
2132 uint8 * ascii85_p = 0; /* Holds ASCII85 encoded data */
2133 #endif
2134
2135 PS_Lvl2colorspace(fd, tif);
2136 use_rawdata = PS_Lvl2ImageDict(fd, tif, w, h);
2137
2138 /* See http://bugzilla.remotesensing.org/show_bug.cgi?id=80 */
2139 #ifdef ENABLE_BROKEN_BEGINENDDATA
2140 fputs("%%BeginData:\n", fd);
2141 #endif
2142 fputs("exec\n", fd);
2143
2144 tiled_image = TIFFIsTiled(tif);
2145 if (tiled_image) {
2146 num_chunks = TIFFNumberOfTiles(tif);
2147 TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &bc);
2148 } else {
2149 num_chunks = TIFFNumberOfStrips(tif);
2150 TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
2151 }
2152
2153 if (use_rawdata) {
2154 chunk_size = (tsize_t) bc[0];
2155 for (chunk_no = 1; chunk_no < num_chunks; chunk_no++)
2156 if ((tsize_t) bc[chunk_no] > chunk_size)
2157 chunk_size = (tsize_t) bc[chunk_no];
2158 } else {
2159 if (tiled_image)
2160 chunk_size = TIFFTileSize(tif);
2161 else
2162 chunk_size = TIFFStripSize(tif);
2163 }
2164 buf_data = (unsigned char *)_TIFFmalloc(chunk_size);
2165 if (!buf_data) {
2166 TIFFError(filename, "Can't alloc %lu bytes for %s.",
2167 (unsigned long) chunk_size, tiled_image ? "tiles" : "strips");
2168 return(FALSE);
2169 }
2170
2171 #if defined( EXP_ASCII85ENCODER )
2172 if ( ascii85 ) {
2173 /*
2174 * Allocate a buffer to hold the ASCII85 encoded data. Note
2175 * that it is allocated with sufficient room to hold the
2176 * encoded data (5*chunk_size/4) plus the EOD marker (+8)
2177 * and formatting line breaks. The line breaks are more
2178 * than taken care of by using 6*chunk_size/4 rather than
2179 * 5*chunk_size/4.
2180 */
2181
2182 ascii85_p = _TIFFmalloc( (chunk_size+(chunk_size/2)) + 8 );
2183
2184 if ( !ascii85_p ) {
2185 _TIFFfree( buf_data );
2186
2187 TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
2188 return ( FALSE );
2189 }
2190 }
2191 #endif
2192
2193 TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
2194 for (chunk_no = 0; chunk_no < num_chunks; chunk_no++) {
2195 if (ascii85)
2196 Ascii85Init();
2197 else
2198 breaklen = MAXLINE;
2199 if (use_rawdata) {
2200 if (tiled_image)
2201 byte_count = TIFFReadRawTile(tif, chunk_no,
2202 buf_data, chunk_size);
2203 else
2204 byte_count = TIFFReadRawStrip(tif, chunk_no,
2205 buf_data, chunk_size);
2206 if (fillorder == FILLORDER_LSB2MSB)
2207 TIFFReverseBits(buf_data, byte_count);
2208 } else {
2209 if (tiled_image)
2210 byte_count = TIFFReadEncodedTile(tif,
2211 chunk_no, buf_data,
2212 chunk_size);
2213 else
2214 byte_count = TIFFReadEncodedStrip(tif,
2215 chunk_no, buf_data,
2216 chunk_size);
2217 }
2218 if (byte_count < 0) {
2219 TIFFError(filename, "Can't read %s %d.",
2220 tiled_image ? "tile" : "strip", chunk_no);
2221 if (ascii85)
2222 Ascii85Put('\0', fd);
2223 }
2224 /*
2225 * for 16 bits, the two bytes must be most significant
2226 * byte first
2227 */
2228 if (bitspersample == 16 && !TIFFIsBigEndian(tif)) {
2229 PS_FlipBytes(buf_data, byte_count);
2230 }
2231 /*
2232 * For images with alpha, matte against a white background;
2233 * i.e. Cback * (1 - Aimage) where Cback = 1. We will fill the
2234 * lower part of the buffer with the modified values.
2235 *
2236 * XXX: needs better solution
2237 */
2238 if (alpha) {
2239 int adjust, i, j = 0;
2240 int ncomps = samplesperpixel - extrasamples;
2241 for (i = 0; i < byte_count; i+=samplesperpixel) {
2242 adjust = 255 - buf_data[i + ncomps];
2243 switch (ncomps) {
2244 case 1:
2245 buf_data[j++] = buf_data[i] + adjust;
2246 break;
2247 case 2:
2248 buf_data[j++] = buf_data[i] + adjust;
2249 buf_data[j++] = buf_data[i+1] + adjust;
2250 break;
2251 case 3:
2252 buf_data[j++] = buf_data[i] + adjust;
2253 buf_data[j++] = buf_data[i+1] + adjust;
2254 buf_data[j++] = buf_data[i+2] + adjust;
2255 break;
2256 }
2257 }
2258 byte_count -= j;
2259 }
2260
2261 if (ascii85) {
2262 #if defined( EXP_ASCII85ENCODER )
2263 ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, buf_data, byte_count );
2264
2265 if ( ascii85_l > 0 )
2266 fwrite( ascii85_p, ascii85_l, 1, fd );
2267 #else
2268 for (cp = buf_data; byte_count > 0; byte_count--)
2269 Ascii85Put(*cp++, fd);
2270 #endif
2271 }
2272 else
2273 {
2274 for (cp = buf_data; byte_count > 0; byte_count--) {
2275 putc(hex[((*cp)>>4)&0xf], fd);
2276 putc(hex[(*cp)&0xf], fd);
2277 cp++;
2278
2279 if (--breaklen <= 0) {
2280 putc('\n', fd);
2281 breaklen = MAXLINE;
2282 }
2283 }
2284 }
2285
2286 if ( !ascii85 ) {
2287 if ( level2 || level3 )
2288 putc( '>', fd );
2289 putc('\n', fd);
2290 }
2291 #if !defined( EXP_ASCII85ENCODER )
2292 else
2293 Ascii85Flush(fd);
2294 #endif
2295 }
2296
2297 #if defined( EXP_ASCII85ENCODER )
2298 if ( ascii85_p )
2299 _TIFFfree( ascii85_p );
2300 #endif
2301
2302 _TIFFfree(buf_data);
2303 #ifdef ENABLE_BROKEN_BEGINENDDATA
2304 fputs("%%EndData\n", fd);
2305 #endif
2306 return(TRUE);
2307 }
2308
2309 void
2310 PSpage(FILE* fd, TIFF* tif, uint32 w, uint32 h)
2311 {
2312 char * imageOp = "image";
2313
2314 if ( useImagemask && (bitspersample == 1) )
2315 imageOp = "imagemask";
2316
2317 if ((level2 || level3) && PS_Lvl2page(fd, tif, w, h))
2318 return;
2319 ps_bytesperrow = tf_bytesperrow - (extrasamples * bitspersample / 8)*w;
2320 switch (photometric) {
2321 case PHOTOMETRIC_RGB:
2322 if (planarconfiguration == PLANARCONFIG_CONTIG) {
2323 fprintf(fd, "%s", RGBcolorimage);
2324 PSColorContigPreamble(fd, w, h, 3);
2325 PSDataColorContig(fd, tif, w, h, 3);
2326 } else {
2327 PSColorSeparatePreamble(fd, w, h, 3);
2328 PSDataColorSeparate(fd, tif, w, h, 3);
2329 }
2330 break;
2331 case PHOTOMETRIC_SEPARATED:
2332 /* XXX should emit CMYKcolorimage */
2333 if (planarconfiguration == PLANARCONFIG_CONTIG) {
2334 PSColorContigPreamble(fd, w, h, 4);
2335 PSDataColorContig(fd, tif, w, h, 4);
2336 } else {
2337 PSColorSeparatePreamble(fd, w, h, 4);
2338 PSDataColorSeparate(fd, tif, w, h, 4);
2339 }
2340 break;
2341 case PHOTOMETRIC_PALETTE:
2342 fprintf(fd, "%s", RGBcolorimage);
2343 PhotoshopBanner(fd, w, h, 1, 3, "false 3 colorimage");
2344 fprintf(fd, "/scanLine %ld string def\n",
2345 (long) ps_bytesperrow * 3L);
2346 fprintf(fd, "%lu %lu 8\n",
2347 (unsigned long) w, (unsigned long) h);
2348 fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
2349 (unsigned long) w, (unsigned long) h, (unsigned long) h);
2350 fprintf(fd, "{currentfile scanLine readhexstring pop} bind\n");
2351 fprintf(fd, "false 3 colorimage\n");
2352 PSDataPalette(fd, tif, w, h);
2353 break;
2354 case PHOTOMETRIC_MINISBLACK:
2355 case PHOTOMETRIC_MINISWHITE:
2356 PhotoshopBanner(fd, w, h, 1, 1, imageOp);
2357 fprintf(fd, "/scanLine %ld string def\n",
2358 (long) ps_bytesperrow);
2359 fprintf(fd, "%lu %lu %d\n",
2360 (unsigned long) w, (unsigned long) h, bitspersample);
2361 fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
2362 (unsigned long) w, (unsigned long) h, (unsigned long) h);
2363 fprintf(fd,
2364 "{currentfile scanLine readhexstring pop} bind\n");
2365 fprintf(fd, "%s\n", imageOp);
2366 PSDataBW(fd, tif, w, h);
2367 break;
2368 }
2369 putc('\n', fd);
2370 }
2371
2372 void
2373 PSColorContigPreamble(FILE* fd, uint32 w, uint32 h, int nc)
2374 {
2375 ps_bytesperrow = nc * (tf_bytesperrow / samplesperpixel);
2376 PhotoshopBanner(fd, w, h, 1, nc, "false %d colorimage");
2377 fprintf(fd, "/line %ld string def\n", (long) ps_bytesperrow);
2378 fprintf(fd, "%lu %lu %d\n",
2379 (unsigned long) w, (unsigned long) h, bitspersample);
2380 fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n",
2381 (unsigned long) w, (unsigned long) h, (unsigned long) h);
2382 fprintf(fd, "{currentfile line readhexstring pop} bind\n");
2383 fprintf(fd, "false %d colorimage\n", nc);
2384 }
2385
2386 void
2387 PSColorSeparatePreamble(FILE* fd, uint32 w, uint32 h, int nc)
2388 {
2389 int i;
2390
2391 PhotoshopBanner(fd, w, h, ps_bytesperrow, nc, "true %d colorimage");
2392 for (i = 0; i < nc; i++)
2393 fprintf(fd, "/line%d %ld string def\n",
2394 i, (long) ps_bytesperrow);
2395 fprintf(fd, "%lu %lu %d\n",
2396 (unsigned long) w, (unsigned long) h, bitspersample);
2397 fprintf(fd, "[%lu 0 0 -%lu 0 %lu] \n",
2398 (unsigned long) w, (unsigned long) h, (unsigned long) h);
2399 for (i = 0; i < nc; i++)
2400 fprintf(fd, "{currentfile line%d readhexstring pop}bind\n", i);
2401 fprintf(fd, "true %d colorimage\n", nc);
2402 }
2403
2404 #define DOBREAK(len, howmany, fd) \
2405 if (((len) -= (howmany)) <= 0) { \
2406 putc('\n', fd); \
2407 (len) = MAXLINE-(howmany); \
2408 }
2409 #define PUTHEX(c,fd) putc(hex[((c)>>4)&0xf],fd); putc(hex[(c)&0xf],fd)
2410
2411 void
2412 PSDataColorContig(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
2413 {
2414 uint32 row;
2415 int breaklen = MAXLINE, es = samplesperpixel - nc;
2416 tsize_t cc;
2417 unsigned char *tf_buf;
2418 unsigned char *cp, c;
2419
2420 (void) w;
2421 tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
2422 if (tf_buf == NULL) {
2423 TIFFError(filename, "No space for scanline buffer");
2424 return;
2425 }
2426 for (row = 0; row < h; row++) {
2427 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
2428 break;
2429 cp = tf_buf;
2430 /*
2431 * for 16 bits, the two bytes must be most significant
2432 * byte first
2433 */
2434 if (bitspersample == 16 && !HOST_BIGENDIAN) {
2435 PS_FlipBytes(cp, tf_bytesperrow);
2436 }
2437 if (alpha) {
2438 int adjust;
2439 cc = 0;
2440 for (; cc < tf_bytesperrow; cc += samplesperpixel) {
2441 DOBREAK(breaklen, nc, fd);
2442 /*
2443 * For images with alpha, matte against
2444 * a white background; i.e.
2445 * Cback * (1 - Aimage)
2446 * where Cback = 1.
2447 */
2448 adjust = 255 - cp[nc];
2449 switch (nc) {
2450 case 4: c = *cp++ + adjust; PUTHEX(c,fd);
2451 case 3: c = *cp++ + adjust; PUTHEX(c,fd);
2452 case 2: c = *cp++ + adjust; PUTHEX(c,fd);
2453 case 1: c = *cp++ + adjust; PUTHEX(c,fd);
2454 }
2455 cp += es;
2456 }
2457 } else {
2458 cc = 0;
2459 for (; cc < tf_bytesperrow; cc += samplesperpixel) {
2460 DOBREAK(breaklen, nc, fd);
2461 switch (nc) {
2462 case 4: c = *cp++; PUTHEX(c,fd);
2463 case 3: c = *cp++; PUTHEX(c,fd);
2464 case 2: c = *cp++; PUTHEX(c,fd);
2465 case 1: c = *cp++; PUTHEX(c,fd);
2466 }
2467 cp += es;
2468 }
2469 }
2470 }
2471 _TIFFfree((char *) tf_buf);
2472 }
2473
2474 void
2475 PSDataColorSeparate(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc)
2476 {
2477 uint32 row;
2478 int breaklen = MAXLINE;
2479 tsize_t cc;
2480 tsample_t s, maxs;
2481 unsigned char *tf_buf;
2482 unsigned char *cp, c;
2483
2484 (void) w;
2485 tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
2486 if (tf_buf == NULL) {
2487 TIFFError(filename, "No space for scanline buffer");
2488 return;
2489 }
2490 maxs = (samplesperpixel > nc ? nc : samplesperpixel);
2491 for (row = 0; row < h; row++) {
2492 for (s = 0; s < maxs; s++) {
2493 if (TIFFReadScanline(tif, tf_buf, row, s) < 0)
2494 break;
2495 for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
2496 DOBREAK(breaklen, 1, fd);
2497 c = *cp++;
2498 PUTHEX(c,fd);
2499 }
2500 }
2501 }
2502 _TIFFfree((char *) tf_buf);
2503 }
2504
2505 #define PUTRGBHEX(c,fd) \
2506 PUTHEX(rmap[c],fd); PUTHEX(gmap[c],fd); PUTHEX(bmap[c],fd)
2507
2508 void
2509 PSDataPalette(FILE* fd, TIFF* tif, uint32 w, uint32 h)
2510 {
2511 uint16 *rmap, *gmap, *bmap;
2512 uint32 row;
2513 int breaklen = MAXLINE, nc;
2514 tsize_t cc;
2515 unsigned char *tf_buf;
2516 unsigned char *cp, c;
2517
2518 (void) w;
2519 if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) {
2520 TIFFError(filename, "Palette image w/o \"Colormap\" tag");
2521 return;
2522 }
2523 switch (bitspersample) {
2524 case 8: case 4: case 2: case 1:
2525 break;
2526 default:
2527 TIFFError(filename, "Depth %d not supported", bitspersample);
2528 return;
2529 }
2530 nc = 3 * (8 / bitspersample);
2531 tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow);
2532 if (tf_buf == NULL) {
2533 TIFFError(filename, "No space for scanline buffer");
2534 return;
2535 }
2536 if (checkcmap(tif, 1<<bitspersample, rmap, gmap, bmap) == 16) {
2537 int i;
2538 #define CVT(x) ((unsigned short) (((x) * 255) / ((1U<<16)-1)))
2539 for (i = (1<<bitspersample)-1; i >= 0; i--) {
2540 rmap[i] = CVT(rmap[i]);
2541 gmap[i] = CVT(gmap[i]);
2542 bmap[i] = CVT(bmap[i]);
2543 }
2544 #undef CVT
2545 }
2546 for (row = 0; row < h; row++) {
2547 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0)
2548 break;
2549 for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) {
2550 DOBREAK(breaklen, nc, fd);
2551 switch (bitspersample) {
2552 case 8:
2553 c = *cp++; PUTRGBHEX(c, fd);
2554 break;
2555 case 4:
2556 c = *cp++; PUTRGBHEX(c&0xf, fd);
2557 c >>= 4; PUTRGBHEX(c, fd);
2558 break;
2559 case 2:
2560 c = *cp++; PUTRGBHEX(c&0x3, fd);
2561 c >>= 2; PUTRGBHEX(c&0x3, fd);
2562 c >>= 2; PUTRGBHEX(c&0x3, fd);
2563 c >>= 2; PUTRGBHEX(c, fd);
2564 break;
2565 case 1:
2566 c = *cp++; PUTRGBHEX(c&0x1, fd);
2567 c >>= 1; PUTRGBHEX(c&0x1, fd);
2568 c >>= 1; PUTRGBHEX(c&0x1, fd);
2569 c >>= 1; PUTRGBHEX(c&0x1, fd);
2570 c >>= 1; PUTRGBHEX(c&0x1, fd);
2571 c >>= 1; PUTRGBHEX(c&0x1, fd);
2572 c >>= 1; PUTRGBHEX(c&0x1, fd);
2573 c >>= 1; PUTRGBHEX(c, fd);
2574 break;
2575 }
2576 }
2577 }
2578 _TIFFfree((char *) tf_buf);
2579 }
2580
2581 void
2582 PSDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h)
2583 {
2584 int breaklen = MAXLINE;
2585 unsigned char* tf_buf;
2586 unsigned char* cp;
2587 tsize_t stripsize = TIFFStripSize(tif);
2588 tstrip_t s;
2589
2590 #if defined( EXP_ASCII85ENCODER )
2591 tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
2592 uint8 *ascii85_p = 0; /* Holds ASCII85 encoded data */
2593 #endif
2594
2595 (void) w; (void) h;
2596 tf_buf = (unsigned char *) _TIFFmalloc(stripsize);
2597 if (tf_buf == NULL) {
2598 TIFFError(filename, "No space for scanline buffer");
2599 return;
2600 }
2601
2602 // FIXME
2603 memset(tf_buf, 0, stripsize);
2604
2605 #if defined( EXP_ASCII85ENCODER )
2606 if ( ascii85 ) {
2607 /*
2608 * Allocate a buffer to hold the ASCII85 encoded data. Note
2609 * that it is allocated with sufficient room to hold the
2610 * encoded data (5*stripsize/4) plus the EOD marker (+8)
2611 * and formatting line breaks. The line breaks are more
2612 * than taken care of by using 6*stripsize/4 rather than
2613 * 5*stripsize/4.
2614 */
2615
2616 ascii85_p = _TIFFmalloc( (stripsize+(stripsize/2)) + 8 );
2617
2618 if ( !ascii85_p ) {
2619 _TIFFfree( tf_buf );
2620
2621 TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
2622 return;
2623 }
2624 }
2625 #endif
2626
2627 if (ascii85)
2628 Ascii85Init();
2629
2630 for (s = 0; s < TIFFNumberOfStrips(tif); s++) {
2631 tmsize_t cc = TIFFReadEncodedStrip(tif, s, tf_buf, stripsize);
2632 if (cc < 0) {
2633 TIFFError(filename, "Can't read strip");
2634 break;
2635 }
2636 cp = tf_buf;
2637 if (photometric == PHOTOMETRIC_MINISWHITE) {
2638 for (cp += cc; --cp >= tf_buf;)
2639 *cp = ~*cp;
2640 cp++;
2641 }
2642 /*
2643 * for 16 bits, the two bytes must be most significant
2644 * byte first
2645 */
2646 if (bitspersample == 16 && !HOST_BIGENDIAN) {
2647 PS_FlipBytes(cp, cc);
2648 }
2649 if (ascii85) {
2650 #if defined( EXP_ASCII85ENCODER )
2651 if (alpha) {
2652 int adjust, i;
2653 for (i = 0; i < cc; i+=2) {
2654 adjust = 255 - cp[i + 1];
2655 cp[i / 2] = cp[i] + adjust;
2656 }
2657 cc /= 2;
2658 }
2659
2660 ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, cp, cc );
2661
2662 if ( ascii85_l > 0 )
2663 fwrite( ascii85_p, ascii85_l, 1, fd );
2664 #else
2665 while (cc-- > 0)
2666 Ascii85Put(*cp++, fd);
2667 #endif /* EXP_ASCII85_ENCODER */
2668 } else {
2669 unsigned char c;
2670
2671 if (alpha) {
2672 int adjust;
2673 while (cc-- > 0) {
2674 DOBREAK(breaklen, 1, fd);
2675 /*
2676 * For images with alpha, matte against
2677 * a white background; i.e.
2678 * Cback * (1 - Aimage)
2679 * where Cback = 1.
2680 */
2681 adjust = 255 - cp[1];
2682 c = *cp++ + adjust; PUTHEX(c,fd);
2683 cp++, cc--;
2684 }
2685 } else {
2686 while (cc-- > 0) {
2687 c = *cp++;
2688 DOBREAK(breaklen, 1, fd);
2689 PUTHEX(c, fd);
2690 }
2691 }
2692 }
2693 }
2694
2695 if ( !ascii85 )
2696 {
2697 if ( level2 || level3)
2698 fputs(">\n", fd);
2699 }
2700 #if !defined( EXP_ASCII85ENCODER )
2701 else
2702 Ascii85Flush(fd);
2703 #else
2704 if ( ascii85_p )
2705 _TIFFfree( ascii85_p );
2706 #endif
2707
2708 _TIFFfree(tf_buf);
2709 }
2710
2711 void
2712 PSRawDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h)
2713 {
2714 uint64 *bc;
2715 uint32 bufsize;
2716 int breaklen = MAXLINE;
2717 tmsize_t cc;
2718 uint16 fillorder;
2719 unsigned char *tf_buf;
2720 unsigned char *cp, c;
2721 tstrip_t s;
2722
2723 #if defined( EXP_ASCII85ENCODER )
2724 tsize_t ascii85_l; /* Length, in bytes, of ascii85_p[] data */
2725 uint8 * ascii85_p = 0; /* Holds ASCII85 encoded data */
2726 #endif
2727
2728 (void) w; (void) h;
2729 TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
2730 TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc);
2731
2732 /*
2733 * Find largest strip:
2734 */
2735
2736 bufsize = (uint32) bc[0];
2737
2738 for ( s = 0; ++s < (tstrip_t)tf_numberstrips; ) {
2739 if ( bc[s] > bufsize )
2740 bufsize = (uint32) bc[s];
2741 }
2742
2743 tf_buf = (unsigned char*) _TIFFmalloc(bufsize);
2744 if (tf_buf == NULL) {
2745 TIFFError(filename, "No space for strip buffer");
2746 return;
2747 }
2748
2749 #if defined( EXP_ASCII85ENCODER )
2750 if ( ascii85 ) {
2751 /*
2752 * Allocate a buffer to hold the ASCII85 encoded data. Note
2753 * that it is allocated with sufficient room to hold the
2754 * encoded data (5*bufsize/4) plus the EOD marker (+8)
2755 * and formatting line breaks. The line breaks are more
2756 * than taken care of by using 6*bufsize/4 rather than
2757 * 5*bufsize/4.
2758 */
2759
2760 ascii85_p = _TIFFmalloc( (bufsize+(bufsize/2)) + 8 );
2761
2762 if ( !ascii85_p ) {
2763 _TIFFfree( tf_buf );
2764
2765 TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." );
2766 return;
2767 }
2768 }
2769 #endif
2770
2771 for (s = 0; s < (tstrip_t) tf_numberstrips; s++) {
2772 cc = TIFFReadRawStrip(tif, s, tf_buf, (tmsize_t) bc[s]);
2773 if (cc < 0) {
2774 TIFFError(filename, "Can't read strip");
2775 break;
2776 }
2777 if (fillorder == FILLORDER_LSB2MSB)
2778 TIFFReverseBits(tf_buf, cc);
2779 if (!ascii85) {
2780 for (cp = tf_buf; cc > 0; cc--) {
2781 DOBREAK(breaklen, 1, fd);
2782 c = *cp++;
2783 PUTHEX(c, fd);
2784 }
2785 fputs(">\n", fd);
2786 breaklen = MAXLINE;
2787 } else {
2788 Ascii85Init();
2789 #if defined( EXP_ASCII85ENCODER )
2790 ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, tf_buf, cc );
2791
2792 if ( ascii85_l > 0 )
2793 fwrite( ascii85_p, ascii85_l, 1, fd );
2794 #else
2795 for (cp = tf_buf; cc > 0; cc--)
2796 Ascii85Put(*cp++, fd);
2797 Ascii85Flush(fd);
2798 #endif /* EXP_ASCII85ENCODER */
2799 }
2800 }
2801 _TIFFfree((char *) tf_buf);
2802
2803 #if defined( EXP_ASCII85ENCODER )
2804 if ( ascii85_p )
2805 _TIFFfree( ascii85_p );
2806 #endif
2807 }
2808
2809 void
2810 Ascii85Init(void)
2811 {
2812 ascii85breaklen = 2*MAXLINE;
2813 ascii85count = 0;
2814 }
2815
2816 static char*
2817 Ascii85Encode(unsigned char* raw)
2818 {
2819 static char encoded[6];
2820 uint32 word;
2821
2822 word = (((raw[0]<<8)+raw[1])<<16) + (raw[2]<<8) + raw[3];
2823 if (word != 0L) {
2824 uint32 q;
2825 uint16 w1;
2826
2827 q = word / (85L*85*85*85); /* actually only a byte */
2828 encoded[0] = (char) (q + '!');
2829
2830 word -= q * (85L*85*85*85); q = word / (85L*85*85);
2831 encoded[1] = (char) (q + '!');
2832
2833 word -= q * (85L*85*85); q = word / (85*85);
2834 encoded[2] = (char) (q + '!');
2835
2836 w1 = (uint16) (word - q*(85L*85));
2837 encoded[3] = (char) ((w1 / 85) + '!');
2838 encoded[4] = (char) ((w1 % 85) + '!');
2839 encoded[5] = '\0';
2840 } else
2841 encoded[0] = 'z', encoded[1] = '\0';
2842 return (encoded);
2843 }
2844
2845 void
2846 Ascii85Put(unsigned char code, FILE* fd)
2847 {
2848 ascii85buf[ascii85count++] = code;
2849 if (ascii85count >= 4) {
2850 unsigned char* p;
2851 int n;
2852
2853 for (n = ascii85count, p = ascii85buf; n >= 4; n -= 4, p += 4) {
2854 char* cp;
2855 for (cp = Ascii85Encode(p); *cp; cp++) {
2856 putc(*cp, fd);
2857 if (--ascii85breaklen == 0) {
2858 putc('\n', fd);
2859 ascii85breaklen = 2*MAXLINE;
2860 }
2861 }
2862 }
2863 _TIFFmemcpy(ascii85buf, p, n);
2864 ascii85count = n;
2865 }
2866 }
2867
2868 void
2869 Ascii85Flush(FILE* fd)
2870 {
2871 if (ascii85count > 0) {
2872 char* res;
2873 _TIFFmemset(&ascii85buf[ascii85count], 0, 3);
2874 res = Ascii85Encode(ascii85buf);
2875 fwrite(res[0] == 'z' ? "!!!!" : res, ascii85count + 1, 1, fd);
2876 }
2877 fputs("~>\n", fd);
2878 }
2879 #if defined( EXP_ASCII85ENCODER)
2880 \f
2881 #define A85BREAKCNTR ascii85breaklen
2882 #define A85BREAKLEN (2*MAXLINE)
2883
2884 /*****************************************************************************
2885 *
2886 * Name: Ascii85EncodeBlock( ascii85_p, f_eod, raw_p, raw_l )
2887 *
2888 * Description: This routine will encode the raw data in the buffer described
2889 * by raw_p and raw_l into ASCII85 format and store the encoding
2890 * in the buffer given by ascii85_p.
2891 *
2892 * Parameters: ascii85_p - A buffer supplied by the caller which will
2893 * contain the encoded ASCII85 data.
2894 * f_eod - Flag: Nz means to end the encoded buffer with
2895 * an End-Of-Data marker.
2896 * raw_p - Pointer to the buffer of data to be encoded
2897 * raw_l - Number of bytes in raw_p[] to be encoded
2898 *
2899 * Returns: (int) < 0 Error, see errno
2900 * >= 0 Number of bytes written to ascii85_p[].
2901 *
2902 * Notes: An external variable given by A85BREAKCNTR is used to
2903 * determine when to insert newline characters into the
2904 * encoded data. As each byte is placed into ascii85_p this
2905 * external is decremented. If the variable is decrement to
2906 * or past zero then a newline is inserted into ascii85_p
2907 * and the A85BREAKCNTR is then reset to A85BREAKLEN.
2908 * Note: for efficiency reasons the A85BREAKCNTR variable
2909 * is not actually checked on *every* character
2910 * placed into ascii85_p but often only for every
2911 * 5 characters.
2912 *
2913 * THE CALLER IS RESPONSIBLE FOR ENSURING THAT ASCII85_P[] IS
2914 * SUFFICIENTLY LARGE TO THE ENCODED DATA!
2915 * You will need at least 5 * (raw_l/4) bytes plus space for
2916 * newline characters and space for an EOD marker (if
2917 * requested). A safe calculation is to use 6*(raw_l/4) + 8
2918 * to size ascii85_p.
2919 *
2920 *****************************************************************************/
2921
2922 tsize_t Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, tsize_t raw_l )
2923
2924 {
2925 char ascii85[5]; /* Encoded 5 tuple */
2926 tsize_t ascii85_l; /* Number of bytes written to ascii85_p[] */
2927 int rc; /* Return code */
2928 uint32 val32; /* Unencoded 4 tuple */
2929
2930 ascii85_l = 0; /* Nothing written yet */
2931
2932 if ( raw_p )
2933 {
2934 --raw_p; /* Prepare for pre-increment fetches */
2935
2936 for ( ; raw_l > 3; raw_l -= 4 )
2937 {
2938 val32 = *(++raw_p) << 24;
2939 val32 += *(++raw_p) << 16;
2940 val32 += *(++raw_p) << 8;
2941 val32 += *(++raw_p);
2942
2943 if ( val32 == 0 ) /* Special case */
2944 {
2945 ascii85_p[ascii85_l] = 'z';
2946 rc = 1;
2947 }
2948
2949 else
2950 {
2951 ascii85[4] = (char) ((val32 % 85) + 33);
2952 val32 /= 85;
2953
2954 ascii85[3] = (char) ((val32 % 85) + 33);
2955 val32 /= 85;
2956
2957 ascii85[2] = (char) ((val32 % 85) + 33);
2958 val32 /= 85;
2959
2960 ascii85[1] = (char) ((val32 % 85) + 33);
2961 ascii85[0] = (char) ((val32 / 85) + 33);
2962
2963 _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, sizeof(ascii85) );
2964 rc = sizeof(ascii85);
2965 }
2966
2967 ascii85_l += rc;
2968
2969 if ( (A85BREAKCNTR -= rc) <= 0 )
2970 {
2971 ascii85_p[ascii85_l] = '\n';
2972 ++ascii85_l;
2973 A85BREAKCNTR = A85BREAKLEN;
2974 }
2975 }
2976
2977 /*
2978 * Output any straggler bytes:
2979 */
2980
2981 if ( raw_l > 0 )
2982 {
2983 tsize_t len; /* Output this many bytes */
2984
2985 len = raw_l + 1;
2986 val32 = *++raw_p << 24; /* Prime the pump */
2987
2988 if ( --raw_l > 0 ) val32 += *(++raw_p) << 16;
2989 if ( --raw_l > 0 ) val32 += *(++raw_p) << 8;
2990
2991 val32 /= 85;
2992
2993 ascii85[3] = (char) ((val32 % 85) + 33);
2994 val32 /= 85;
2995
2996 ascii85[2] = (char) ((val32 % 85) + 33);
2997 val32 /= 85;
2998
2999 ascii85[1] = (char) ((val32 % 85) + 33);
3000 ascii85[0] = (char) ((val32 / 85) + 33);
3001
3002 _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, len );
3003 ascii85_l += len;
3004 }
3005 }
3006
3007 /*
3008 * If requested add an ASCII85 End Of Data marker:
3009 */
3010
3011 if ( f_eod )
3012 {
3013 ascii85_p[ascii85_l++] = '~';
3014 ascii85_p[ascii85_l++] = '>';
3015 ascii85_p[ascii85_l++] = '\n';
3016 }
3017
3018 return ( ascii85_l );
3019
3020 } /* Ascii85EncodeBlock() */
3021
3022 #endif /* EXP_ASCII85ENCODER */
3023
3024
3025 char* stuff[] = {
3026 "usage: tiff2ps [options] input.tif ...",
3027 "where options are:",
3028 " -1 generate PostScript Level 1 (default)",
3029 " -2 generate PostScript Level 2",
3030 " -3 generate PostScript Level 3",
3031 " -8 disable use of ASCII85 encoding with PostScript Level 2/3",
3032 " -a convert all directories in file (default is first), Not EPS",
3033 " -b # set the bottom margin to # inches",
3034 " -c center image (-b and -l still add to this)",
3035 " -d # set initial directory to # counting from zero",
3036 " -D enable duplex printing (two pages per sheet of paper)",
3037 " -e generate Encapsulated PostScript (EPS) (implies -z)",
3038 " -h # set printed page height to # inches (no default)",
3039 " -w # set printed page width to # inches (no default)",
3040 " -H # split image if height is more than # inches",
3041 " -P L or P set optional PageOrientation DSC comment to Landscape or Portrait",
3042 " -W # split image if width is more than # inches",
3043 " -L # overLap split images by # inches",
3044 " -i # enable/disable (Nz/0) pixel interpolation (default: enable)",
3045 " -l # set the left margin to # inches",
3046 " -m use \"imagemask\" operator instead of \"image\"",
3047 " -o # convert directory at file offset # bytes",
3048 " -O file write PostScript to file instead of standard output",
3049 " -p generate regular PostScript",
3050 " -r # or auto rotate by 90, 180, 270 degrees or auto",
3051 " -s generate PostScript for a single image",
3052 " -t name set postscript document title. Otherwise the filename is used",
3053 " -T print pages for top edge binding",
3054 " -x override resolution units as centimeters",
3055 " -y override resolution units as inches",
3056 " -z enable printing in the deadzone (only for PostScript Level 2/3)",
3057 NULL
3058 };
3059
3060 static void
3061 usage(int code)
3062 {
3063 char buf[BUFSIZ];
3064 int i;
3065
3066 setbuf(stderr, buf);
3067 fprintf(stderr, "%s\n\n", TIFFGetVersion());
3068 for (i = 0; stuff[i] != NULL; i++)
3069 fprintf(stderr, "%s\n", stuff[i]);
3070 exit(code);
3071 }
3072