1/* $Id: tiff2ps.c 276 2010-06-30 12:18:30Z nijtmans $ */ 2 3/* 4 * Copyright (c) 1988-1997 Sam Leffler 5 * Copyright (c) 1991-1997 Silicon Graphics, Inc. 6 * 7 * Permission to use, copy, modify, distribute, and sell this software and 8 * its documentation for any purpose is hereby granted without fee, provided 9 * that (i) the above copyright notices and this permission notice appear in 10 * all copies of the software and related documentation, and (ii) the names of 11 * Sam Leffler and Silicon Graphics may not be used in any advertising or 12 * publicity relating to the software without the specific, prior written 13 * permission of Sam Leffler and Silicon Graphics. 14 * 15 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 16 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 17 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. 18 * 19 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR 20 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, 21 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, 22 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 23 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 24 * OF THIS SOFTWARE. 25 */ 26 27#include "tif_config.h" 28 29#include <stdio.h> 30#include <stdlib.h> /* for atof */ 31#include <math.h> 32#include <time.h> 33#include <string.h> 34 35#ifdef HAVE_UNISTD_H 36# include <unistd.h> 37#endif 38 39#include "tiffio.h" 40 41/* 42 * Revision history 43 * 44 * 2005-June-3 45 * Richard Nolde: Added support for rotations of 90, 180, 270 46 * and auto using -r <90|180|270|auto>. Auto picks the best 47 * fit for the image on the specified paper size (eg portrait 48 * or landscape) if -h or -w is specified. Rotation is in 49 * degrees counterclockwise since that is how Postscript does 50 * it. Auto rotates 90 degrees ccw to produce landscape. 51 * 52 * Added maxPageWidth option using -W flag. MaxPageHeight and 53 * MaxPageWidth are mutually exclusive since the aspect ratio 54 * cannot be maintained if you set both. 55 * Rewrote PlaceImage to allow maxPageHeight and maxPageWidth 56 * options to work with values smaller or larger than the 57 * physical paper size and still preserve the aspect ratio. 58 * This is accomplished by creating multiple pages across 59 * as well as down if need be. 60 * 61 * 2001-Mar-21 62 * I (Bruce A. Mallett) added this revision history comment ;) 63 * 64 * Fixed PS_Lvl2page() code which outputs non-ASCII85 raw 65 * data. Moved test for when to output a line break to 66 * *after* the output of a character. This just serves 67 * to fix an eye-nuisance where the first line of raw 68 * data was one character shorter than subsequent lines. 69 * 70 * Added an experimental ASCII85 encoder which can be used 71 * only when there is a single buffer of bytes to be encoded. 72 * This version is much faster at encoding a straight-line 73 * buffer of data because it can avoid alot of the loop 74 * overhead of the byte-by-bye version. To use this version 75 * you need to define EXP_ASCII85ENCODER (experimental ...). 76 * 77 * Added bug fix given by Michael Schmidt to PS_Lvl2page() 78 * in which an end-of-data marker ('>') was not being output 79 * when producing non-ASCII85 encoded PostScript Level 2 80 * data. 81 * 82 * Fixed PS_Lvl2colorspace() so that it no longer assumes that 83 * a TIFF having more than 2 planes is a CMYK. This routine 84 * no longer looks at the samples per pixel but instead looks 85 * at the "photometric" value. This change allows support of 86 * CMYK TIFFs. 87 * 88 * Modified the PostScript L2 imaging loop so as to test if 89 * the input stream is still open before attempting to do a 90 * flushfile on it. This was done because some RIPs close 91 * the stream after doing the image operation. 92 * 93 * Got rid of the realloc() being done inside a loop in the 94 * PSRawDataBW() routine. The code now walks through the 95 * byte-size array outside the loop to determine the largest 96 * size memory block that will be needed. 97 * 98 * Added "-m" switch to ask tiff2ps to, where possible, use the 99 * "imagemask" operator instead of the "image" operator. 100 * 101 * Added the "-i #" switch to allow interpolation to be disabled. 102 * 103 * Unrolled a loop or two to improve performance. 104 */ 105 106/* 107 * Define EXP_ASCII85ENCODER if you want to use an experimental 108 * version of the ASCII85 encoding routine. The advantage of 109 * using this routine is that tiff2ps will convert to ASCII85 110 * encoding at between 3 and 4 times the speed as compared to 111 * using the old (non-experimental) encoder. The disadvantage 112 * is that you will be using a new (and unproven) encoding 113 * routine. So user beware, you have been warned! 114 */ 115 116#define EXP_ASCII85ENCODER 117 118/* 119 * NB: this code assumes uint32 works with printf's %l[ud]. 120 */ 121#ifndef TRUE 122#define TRUE 1 123#define FALSE 0 124#endif 125 126#define HORIZONTAL 1 127#define VERTICAL 2 128 129int ascii85 = FALSE; /* use ASCII85 encoding */ 130int interpolate = TRUE; /* interpolate level2 image */ 131int level2 = FALSE; /* generate PostScript level 2 */ 132int level3 = FALSE; /* generate PostScript level 3 */ 133int printAll = FALSE; /* print all images in file */ 134int generateEPSF = TRUE; /* generate Encapsulated PostScript */ 135int PSduplex = FALSE; /* enable duplex printing */ 136int PStumble = FALSE; /* enable top edge binding */ 137int PSavoiddeadzone = TRUE; /* enable avoiding printer deadzone */ 138double maxPageHeight = 0; /* maximum height to select from image and print per page */ 139double maxPageWidth = 0; /* maximum width to select from image and print per page */ 140double splitOverlap = 0; /* amount for split pages to overlag */ 141int rotate = FALSE; /* rotate image by angle 90, 180, 270 degrees */ 142int rotation = 0; /* optional value for rotation angle */ 143char *filename; /* input filename */ 144int useImagemask = FALSE; /* Use imagemask instead of image operator */ 145uint16 res_unit = 0; /* Resolution units: 2 - inches, 3 - cm */ 146 147/* 148 * ASCII85 Encoding Support. 149 */ 150unsigned char ascii85buf[10]; 151int ascii85count; 152int ascii85breaklen; 153 154int TIFF2PS(FILE*, TIFF*, double, double, double, double, int); 155void PSpage(FILE*, TIFF*, uint32, uint32); 156void PSColorContigPreamble(FILE*, uint32, uint32, int); 157void PSColorSeparatePreamble(FILE*, uint32, uint32, int); 158void PSDataColorContig(FILE*, TIFF*, uint32, uint32, int); 159void PSDataColorSeparate(FILE*, TIFF*, uint32, uint32, int); 160void PSDataPalette(FILE*, TIFF*, uint32, uint32); 161void PSDataBW(FILE*, TIFF*, uint32, uint32); 162void PSRawDataBW(FILE*, TIFF*, uint32, uint32); 163void Ascii85Init(void); 164void Ascii85Put(unsigned char code, FILE* fd); 165void Ascii85Flush(FILE* fd); 166void PSHead(FILE*, TIFF*, uint32, uint32, double, double, double, double); 167void PSTail(FILE*, int); 168 169#if defined( EXP_ASCII85ENCODER) 170int Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, int raw_l ); 171#endif 172 173static void usage(int); 174 175int 176main(int argc, char* argv[]) 177{ 178 int dirnum = -1, c, np = 0; 179 int centered = 0; 180 double bottommargin = 0; 181 double leftmargin = 0; 182 double pageWidth = 0; 183 double pageHeight = 0; 184 uint32 diroff = 0; 185 extern char *optarg; 186 extern int optind; 187 FILE* output = stdout; 188 189 while ((c = getopt(argc, argv, "b:d:h:H:W:L:i:w:l:o:O:r:acelmxyzps1238DT")) != -1) 190 switch (c) { 191 case 'b': 192 bottommargin = atof(optarg); 193 break; 194 case 'c': 195 centered = 1; 196 break; 197 case 'd': 198 dirnum = atoi(optarg); 199 break; 200 case 'D': 201 PSduplex = TRUE; 202 break; 203 case 'i': 204 interpolate = atoi(optarg) ? TRUE:FALSE; 205 break; 206 case 'T': 207 PStumble = TRUE; 208 break; 209 case 'e': 210 PSavoiddeadzone = FALSE; 211 generateEPSF = TRUE; 212 break; 213 case 'h': 214 pageHeight = atof(optarg); 215 break; 216 case 'H': 217 maxPageHeight = atof(optarg); 218 if (pageHeight==0) pageHeight = maxPageHeight; 219 break; 220 case 'W': 221 maxPageWidth = atof(optarg); 222 if (pageWidth==0) pageWidth = maxPageWidth; 223 break; 224 case 'L': 225 splitOverlap = atof(optarg); 226 break; 227 case 'm': 228 useImagemask = TRUE; 229 break; 230 case 'o': 231 diroff = (uint32) strtoul(optarg, NULL, 0); 232 break; 233 case 'O': /* XXX too bad -o is already taken */ 234 output = fopen(optarg, "w"); 235 if (output == NULL) { 236 fprintf(stderr, 237 "%s: %s: Cannot open output file.\n", 238 argv[0], optarg); 239 exit(-2); 240 } 241 break; 242 case 'l': 243 leftmargin = atof(optarg); 244 break; 245 case 'a': 246 printAll = TRUE; 247 /* fall thru... */ 248 case 'p': 249 generateEPSF = FALSE; 250 break; 251 case 'r': 252 rotate = TRUE; 253 if (strcmp (optarg, "auto") == 0) 254 rotation = 0; 255 else 256 rotation = atoi(optarg); 257 switch (rotation) 258 { 259 case 0: 260 case 90: 261 case 180: 262 case 270: 263 break; 264 default: 265 fprintf (stderr, "Rotation angle must be 90, 180, 270 (degrees ccw) or auto\n"); 266 exit (-2); 267 } 268 break; 269 case 's': 270 printAll = FALSE; 271 break; 272 case 'w': 273 pageWidth = atof(optarg); 274 break; 275 case 'z': 276 PSavoiddeadzone = FALSE; 277 break; 278 case '1': 279 level2 = FALSE; 280 level3 = FALSE; 281 ascii85 = FALSE; 282 break; 283 case '2': 284 level2 = TRUE; 285 ascii85 = TRUE; /* default to yes */ 286 break; 287 case '3': 288 level3 = TRUE; 289 ascii85 = TRUE; /* default to yes */ 290 break; 291 case '8': 292 ascii85 = FALSE; 293 break; 294 case 'x': 295 res_unit = RESUNIT_CENTIMETER; 296 break; 297 case 'y': 298 res_unit = RESUNIT_INCH; 299 break; 300 case '?': 301 usage(-1); 302 } 303 for (; argc - optind > 0; optind++) { 304 TIFF* tif = TIFFOpen(filename = argv[optind], "r"); 305 if (tif != NULL) { 306 if (dirnum != -1 307 && !TIFFSetDirectory(tif, (tdir_t)dirnum)) 308 return (-1); 309 else if (diroff != 0 && 310 !TIFFSetSubDirectory(tif, diroff)) 311 return (-1); 312 np = TIFF2PS(output, tif, pageWidth, pageHeight, 313 leftmargin, bottommargin, centered); 314 TIFFClose(tif); 315 } 316 } 317 if (np) 318 PSTail(output, np); 319 else 320 usage(-1); 321 if (output != stdout) 322 fclose(output); 323 return (0); 324} 325 326static uint16 samplesperpixel; 327static uint16 bitspersample; 328static uint16 planarconfiguration; 329static uint16 photometric; 330static uint16 compression; 331static uint16 extrasamples; 332static int alpha; 333 334static int 335checkImage(TIFF* tif) 336{ 337 switch (photometric) { 338 case PHOTOMETRIC_YCBCR: 339 if ((compression == COMPRESSION_JPEG || compression == COMPRESSION_OJPEG) 340 && planarconfiguration == PLANARCONFIG_CONTIG) { 341 /* can rely on libjpeg to convert to RGB */ 342 TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE, 343 JPEGCOLORMODE_RGB); 344 photometric = PHOTOMETRIC_RGB; 345 } else { 346 if (level2 || level3) 347 break; 348 TIFFError(filename, "Can not handle image with %s", 349 "PhotometricInterpretation=YCbCr"); 350 return (0); 351 } 352 /* fall thru... */ 353 case PHOTOMETRIC_RGB: 354 if (alpha && bitspersample != 8) { 355 TIFFError(filename, 356 "Can not handle %d-bit/sample RGB image with alpha", 357 bitspersample); 358 return (0); 359 } 360 /* fall thru... */ 361 case PHOTOMETRIC_SEPARATED: 362 case PHOTOMETRIC_PALETTE: 363 case PHOTOMETRIC_MINISBLACK: 364 case PHOTOMETRIC_MINISWHITE: 365 break; 366 case PHOTOMETRIC_LOGL: 367 case PHOTOMETRIC_LOGLUV: 368 if (compression != COMPRESSION_SGILOG && 369 compression != COMPRESSION_SGILOG24) { 370 TIFFError(filename, 371 "Can not handle %s data with compression other than SGILog", 372 (photometric == PHOTOMETRIC_LOGL) ? 373 "LogL" : "LogLuv" 374 ); 375 return (0); 376 } 377 /* rely on library to convert to RGB/greyscale */ 378 TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT); 379 photometric = (photometric == PHOTOMETRIC_LOGL) ? 380 PHOTOMETRIC_MINISBLACK : PHOTOMETRIC_RGB; 381 bitspersample = 8; 382 break; 383 case PHOTOMETRIC_CIELAB: 384 /* fall thru... */ 385 default: 386 TIFFError(filename, 387 "Can not handle image with PhotometricInterpretation=%d", 388 photometric); 389 return (0); 390 } 391 switch (bitspersample) { 392 case 1: case 2: 393 case 4: case 8: 394 case 16: 395 break; 396 default: 397 TIFFError(filename, "Can not handle %d-bit/sample image", 398 bitspersample); 399 return (0); 400 } 401 if (planarconfiguration == PLANARCONFIG_SEPARATE && extrasamples > 0) 402 TIFFWarning(filename, "Ignoring extra samples"); 403 return (1); 404} 405 406#define PS_UNIT_SIZE 72.0F 407#define PSUNITS(npix,res) ((npix) * (PS_UNIT_SIZE / (res))) 408 409static char RGBcolorimage[] = "\ 410/bwproc {\n\ 411 rgbproc\n\ 412 dup length 3 idiv string 0 3 0\n\ 413 5 -1 roll {\n\ 414 add 2 1 roll 1 sub dup 0 eq {\n\ 415 pop 3 idiv\n\ 416 3 -1 roll\n\ 417 dup 4 -1 roll\n\ 418 dup 3 1 roll\n\ 419 5 -1 roll put\n\ 420 1 add 3 0\n\ 421 } { 2 1 roll } ifelse\n\ 422 } forall\n\ 423 pop pop pop\n\ 424} def\n\ 425/colorimage where {pop} {\n\ 426 /colorimage {pop pop /rgbproc exch def {bwproc} image} bind def\n\ 427} ifelse\n\ 428"; 429 430/* 431 * Adobe Photoshop requires a comment line of the form: 432 * 433 * %ImageData: <cols> <rows> <depth> <main channels> <pad channels> 434 * <block size> <1 for binary|2 for hex> "data start" 435 * 436 * It is claimed to be part of some future revision of the EPS spec. 437 */ 438static void 439PhotoshopBanner(FILE* fd, uint32 w, uint32 h, int bs, int nc, char* startline) 440{ 441 fprintf(fd, "%%ImageData: %ld %ld %d %d 0 %d 2 \"", 442 (long) w, (long) h, bitspersample, nc, bs); 443 fprintf(fd, startline, nc); 444 fprintf(fd, "\"\n"); 445} 446 447/* 448 * pw : image width in pixels 449 * ph : image height in pixels 450 * pprw : image width in PS units (72 dpi) 451 * pprh : image height in PS units (72 dpi) 452 */ 453static void 454setupPageState(TIFF* tif, uint32* pw, uint32* ph, double* pprw, double* pprh) 455{ 456 float xres = 0.0F, yres = 0.0F; 457 458 TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, pw); 459 TIFFGetField(tif, TIFFTAG_IMAGELENGTH, ph); 460 if (res_unit == 0) 461 TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &res_unit); 462 /* 463 * Calculate printable area. 464 */ 465 if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) 466 || fabs(xres) < 0.0000001) 467 xres = PS_UNIT_SIZE; 468 if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) 469 || fabs(yres) < 0.0000001) 470 yres = PS_UNIT_SIZE; 471 switch (res_unit) { 472 case RESUNIT_CENTIMETER: 473 xres *= 2.54F, yres *= 2.54F; 474 break; 475 case RESUNIT_INCH: 476 break; 477 case RESUNIT_NONE: 478 default: 479 /* 480 * check that the resolution is not inches before scaling it 481 */ 482 if (xres != PS_UNIT_SIZE || yres != PS_UNIT_SIZE) 483 xres *= PS_UNIT_SIZE, yres *= PS_UNIT_SIZE; 484 break; 485 } 486 *pprh = PSUNITS(*ph, yres); 487 *pprw = PSUNITS(*pw, xres); 488} 489 490static int 491isCCITTCompression(TIFF* tif) 492{ 493 uint16 compress; 494 TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress); 495 return (compress == COMPRESSION_CCITTFAX3 || 496 compress == COMPRESSION_CCITTFAX4 || 497 compress == COMPRESSION_CCITTRLE || 498 compress == COMPRESSION_CCITTRLEW); 499} 500 501static tsize_t tf_bytesperrow; 502static tsize_t ps_bytesperrow; 503static tsize_t tf_rowsperstrip; 504static tsize_t tf_numberstrips; 505static char *hex = "0123456789abcdef"; 506 507/* 508 * imagewidth & imageheight are 1/72 inches 509 * pagewidth & pageheight are inches 510 */ 511int 512PlaceImage(TIFF *tif, FILE *fp, int *npages, uint32 w, uint32 h, 513 double pagewidth, double pageheight, 514 double imagewidth, double imageheight, 515 int splitpage, double lm, double bm, int cnt) 516{ 517 int i = 0; 518 int ximages = 0; 519 int splitaxis = 0; 520 double xtran = 0; 521 double ytran = 0; 522 double xscale = 1; 523 double yscale = 1; 524 double left_margin = 0; 525 double bottom_margin = 0; 526 double left_offset = lm * PS_UNIT_SIZE; 527 double bottom_offset = bm * PS_UNIT_SIZE; 528 double splitwidth = 0; 529 double splitheight = 0; 530 double subimageheight = 0; 531 double subimagewidth = 0; 532 double overlap = 0; 533 double overlapspace = 0; 534 535 pagewidth *= PS_UNIT_SIZE; 536 pageheight *= PS_UNIT_SIZE; 537 538 splitheight = maxPageHeight * PS_UNIT_SIZE; 539 splitwidth = maxPageWidth * PS_UNIT_SIZE; 540 overlap = splitOverlap * PS_UNIT_SIZE; 541 /* These have to be mutually exclusive to maintain the aspect ratio */ 542 if (splitheight != 0) 543 splitaxis = VERTICAL; 544 else { 545 if (splitwidth != 0) 546 splitaxis = HORIZONTAL; 547 else { 548 fprintf (stderr, "You must specify either a maximum page height or width\n"); 549 return (0); 550 } 551 } 552 553 if (splitaxis == VERTICAL) { 554 if (imageheight <= splitheight) { 555 /* Simple case, no splitting or scaling for image height */ 556 yscale = imageheight; 557 ytran = pageheight - imageheight; 558 } else { /* imageheight > splitheight */ 559 subimageheight = imageheight - ((splitheight - overlap) * splitpage); 560 561 yscale = imageheight * (pageheight / splitheight); 562 ytran = pageheight - subimageheight * (pageheight / splitheight); 563 564 if (subimageheight > splitheight) { 565 splitpage++; 566 } else { 567 splitpage = 0; 568 } 569 } 570 bottom_offset += ytran / (cnt?2:1); 571 left_margin = left_offset / (cnt ? 2 : 1); 572 /* 573 * WIDTH: We can't rescale height based on width so we need to make multiple 574 * pages from each horizontal segment if the image is wider than pagewidth 575 */ 576 577 ximages = ceil (imagewidth / pagewidth); 578 overlapspace = (ximages - 1) * overlap; 579 if (((imagewidth + overlapspace) * (pageheight / splitheight)) > (ximages * pagewidth)) { 580 ximages++; 581 overlapspace += overlap; 582 } 583 xscale = (imagewidth + overlapspace) * (pageheight / splitheight); 584 if (imagewidth <= pagewidth) { 585 left_offset = left_margin; 586 bottom_offset = bottom_margin; 587 fprintf(fp, "%f %f translate\n", left_offset, bottom_offset); 588 fprintf(fp, "%f %f scale\n", xscale, yscale); 589 } else { 590 for (i = 0; i < ximages; i++) { 591 xtran = i * (pagewidth - ((i > 0) ? overlap : 0)); 592 left_offset = -xtran + left_margin; 593 594 fprintf(fp, "%f %f translate\n", left_offset, bottom_offset); 595 fprintf(fp, "%f %f scale\n", xscale, yscale); 596 597 if ( i < (ximages - 1)) { 598 PSpage(fp, tif, w, h); 599 fprintf(fp, "end\n"); 600 fprintf(fp, "grestore\n"); 601 fprintf(fp, "showpage\n"); 602 (*npages)++; 603 fprintf(fp, "%%%%Page: %d %d\n", (*npages), (*npages)); 604 fprintf(fp, "gsave\n"); 605 fprintf(fp, "100 dict begin\n"); 606 } 607 } 608 } 609 } else { /* splitaxis is HORIZONTAL */ 610 ximages = ceil (imagewidth / splitwidth); 611 overlapspace = (ximages - 1) * overlap; 612 if (((imagewidth + overlapspace) * (pagewidth / splitwidth)) > (ximages * pagewidth)) { 613 ximages++; 614 overlapspace += overlap; 615 } 616 if (ximages == 1) { 617 /* Simple case, no splitting or scaling for image width */ 618 xscale = imagewidth; 619 xtran = 0; 620 splitpage = 0; 621 } else { 622 subimagewidth = imagewidth - ((splitwidth - overlap) * splitpage); 623 624 xscale = imagewidth * (pagewidth / splitwidth); 625 xtran = imagewidth - (subimagewidth * (pagewidth / splitwidth)); 626 627 splitheight = pageheight; 628 subimageheight = imageheight - ((splitheight - overlap) * splitpage); 629 yscale = (imageheight + overlapspace); 630 ytran = pageheight - subimageheight + (overlapspace * (pagewidth / splitwidth)); 631 632 if (subimageheight > splitheight) { 633 splitpage++; 634 } else { 635 splitpage = 0; 636 } 637 } 638 bottom_margin = bottom_offset / (cnt ? 2 : 1); 639 bottom_offset = bottom_margin + ytran; 640 left_margin = left_offset / (cnt ? 2 : 1); 641 if (imagewidth <= pagewidth) { 642 left_offset = left_margin; 643 bottom_offset = bottom_margin; 644 fprintf(fp, "%f %f translate\n", left_offset, bottom_offset); 645 fprintf(fp, "%f %f scale\n", xscale, yscale); 646 } else { 647 for (i = 0; i < ximages; i++) { 648 xtran = i * (pagewidth - ((i > 0) ? overlap : 0)); 649 left_offset = left_margin - xtran; 650 fprintf(fp, "%f %f translate\n", left_offset, bottom_offset); 651 fprintf(fp, "%f %f scale\n", xscale, yscale); 652 if ( i < (ximages - 1)) { 653 PSpage(fp, tif, w, h); 654 fprintf(fp, "end\n"); 655 fprintf(fp, "grestore\n"); 656 fprintf(fp, "showpage\n"); 657 (*npages)++; 658 fprintf(fp, "%%%%Page: %d %d\n", (*npages), (*npages)); 659 fprintf(fp, "gsave\n"); 660 fprintf(fp, "100 dict begin\n"); 661 } 662 } 663 } 664 } 665 666 if (rotate) 667 { 668 if (rotation == 180 ) 669 { 670 fprintf(fp, "%f %f translate\n", left_offset, bottom_offset); 671 fprintf(fp, "%f %f scale\n", xscale, yscale); 672 } 673 else 674 { 675 fprintf(fp, "%f %f translate\n", bottom_offset, left_offset); 676 fprintf(fp, "%f %f scale\n", yscale, xscale); 677 } 678 fprintf (fp, "1 1 translate %d rotate\n", rotation); 679 } 680 681 return splitpage; 682} 683 684/* returns the sequence number of the page processed */ 685int 686TIFF2PS(FILE* fd, TIFF* tif, 687 double pw, double ph, double lm, double bm, int cnt) 688{ 689 uint32 w = 0, h = 0; 690 float ox, oy; 691 double maxsource, maxtarget; /* Used for auto rotations */ 692 double hcenter, vcenter; /* Used for centering */ 693 double prw, prh; /* Original Image width and height in Postscript points */ 694 double psw, psh; /* Scaled image width and height in Postscript points */ 695 double xscale = 1.0, yscale = 1.0, scale = 1.0; 696 double left_offset = lm * PS_UNIT_SIZE; 697 double bottom_offset = bm * PS_UNIT_SIZE; 698 uint32 subfiletype; 699 uint16* sampleinfo; 700 static int npages = 0; 701 int split; 702 703 if (!TIFFGetField(tif, TIFFTAG_XPOSITION, &ox)) 704 ox = 0; 705 if (!TIFFGetField(tif, TIFFTAG_YPOSITION, &oy)) 706 oy = 0; 707 do { 708 tf_numberstrips = TIFFNumberOfStrips(tif); 709 TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, 710 &tf_rowsperstrip); 711 setupPageState(tif, &w, &h, &prw, &prh); 712 if (pw != 0) { 713 psw = pw * PS_UNIT_SIZE; 714 if (res_unit == RESUNIT_CENTIMETER) 715 psw *= 2.54F; 716 } 717 else 718 psw = prw; 719 720 if (ph != 0) { 721 psh = ph * PS_UNIT_SIZE; 722 if (res_unit == RESUNIT_CENTIMETER) 723 psh *= 2.54F; 724 } 725 else 726 psh = prh; 727 728 /* auto rotate for best fit */ 729 if (rotate && rotation == 0) { 730 maxsource = (prw >= prh) ? prw : prh; 731 maxtarget = (psw >= psh) ? psw : psh; 732 if (((maxsource == prw) && (maxtarget != psw)) || 733 ((maxsource == prh) && (maxtarget != psh))) { 734 rotation = 90; 735 } 736 } 737 738 /* scaling depends on rotation and new page size */ 739 switch (rotation) { 740 case 0: 741 case 180: 742 xscale = (psw - left_offset)/prw; 743 yscale = (psh - bottom_offset)/prh; 744 if (!npages) 745 PSHead(fd, tif, w, h, psw, psh, ox, oy); 746 break; 747 case 90: 748 case 270: 749 xscale = (psw - bottom_offset) /prh; 750 yscale = (psh - left_offset) /prw; 751 if (!npages) 752 PSHead(fd, tif, w, h, psh, psw, oy, ox); 753 break; 754 } 755 TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, 756 &bitspersample); 757 TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, 758 &samplesperpixel); 759 TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, 760 &planarconfiguration); 761 TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression); 762 TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, 763 &extrasamples, &sampleinfo); 764 alpha = (extrasamples == 1 && 765 sampleinfo[0] == EXTRASAMPLE_ASSOCALPHA); 766 if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) { 767 switch (samplesperpixel - extrasamples) { 768 case 1: 769 if (isCCITTCompression(tif)) 770 photometric = PHOTOMETRIC_MINISWHITE; 771 else 772 photometric = PHOTOMETRIC_MINISBLACK; 773 break; 774 case 3: 775 photometric = PHOTOMETRIC_RGB; 776 break; 777 case 4: 778 photometric = PHOTOMETRIC_SEPARATED; 779 break; 780 } 781 } 782 if (checkImage(tif)) { 783 tf_bytesperrow = TIFFScanlineSize(tif); 784 npages++; 785 fprintf(fd, "%%%%Page: %d %d\n", npages, npages); 786 if (!generateEPSF && ( level2 || level3 )) { 787 fprintf(fd, 788 "1 dict begin /PageSize [ %f %f ] def currentdict end setpagedevice\n", 789 psw, psh); 790 fputs( 791 "<<\n /Policies <<\n /PageSize 3\n >>\n>> setpagedevice\n", 792 fd); 793 } 794 fprintf(fd, "gsave\n"); 795 fprintf(fd, "100 dict begin\n"); 796 /* N.B. Setting maxPageHeight also sets ph if not set explicitly */ 797 if (pw != 0 || ph != 0) { 798 if (maxPageHeight || maxPageWidth) { /* used -H or -W options */ 799 split = PlaceImage(tif,fd,&npages,w,h,pw,ph,prw,prh, 800 0,lm,bm,cnt); 801 while( split ) { 802 PSpage(fd, tif, w, h); 803 fprintf(fd, "end\n"); 804 fprintf(fd, "grestore\n"); 805 fprintf(fd, "showpage\n"); 806 npages++; 807 fprintf(fd, "%%%%Page: %d %d\n", 808 npages, npages); 809 fprintf(fd, "gsave\n"); 810 fprintf(fd, "100 dict begin\n"); 811 split = PlaceImage(tif,fd,&npages,w,h,pw,ph,prw,prh, 812 split,lm,bm,cnt); 813 } 814 } 815 else { 816 /* NB: maintain image aspect ratio */ 817 scale = (xscale < yscale) ? xscale : yscale; 818 if (scale > 1.0) 819 scale = 1.0; 820 821 /* Adjust offsets for centering */ 822 if (cnt) { 823 switch (rotation) { 824 case 90: 825 case 270: 826 hcenter = (psw - prh * scale) / 2; 827 vcenter = (psh - prw * scale) / 2; 828 break; 829 case 0: 830 case 180: 831 default: 832 hcenter = (psw - prw * scale) / 2; 833 vcenter = (psh - prh * scale) / 2; 834 break; 835 } 836 } 837 else 838 hcenter = 0.0, vcenter = 0.0; 839 if (cnt) 840 fprintf (fd, "%f %f translate\n", hcenter, vcenter); 841 switch (rotation) { 842 case 0: 843 fprintf (fd, "%f %f scale\n", prw * scale, prh * scale); 844 break; 845 case 90: 846 fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", prh * scale, prw * scale); 847 break; 848 case 180: 849 fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", prw * scale, prh * scale); 850 break; 851 case 270: 852 fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", prh * scale, prw * scale); 853 break; 854 default: 855 fprintf (stderr, "Unsupported angle. No rotation\n"); 856 fprintf (fd, "%f %f scale\n", prw * scale, prh * scale); 857 break; 858 } 859 } 860 } else { 861 if (rotate) 862 { 863 /* Width and height have already been enchanged for 90/270 rotations */ 864 switch (rotation) { 865 case 0: 866 fprintf (fd, "%f %f scale\n", prw, prh); 867 case 90: 868 fprintf (fd, "%f %f scale\n1 0 translate 90 rotate\n", prw, prh); 869 break; 870 case 180: 871 fprintf (fd, "%f %f scale\n1 1 translate 180 rotate\n", prw, prh); 872 break; 873 case 270: 874 fprintf (fd, "%f %f scale\n0 1 translate 270 rotate\n", prw, prh); 875 break; 876 default: 877 fprintf (stderr, "Unsupported angle. No rotation\n"); 878 fprintf( fd, "%f %f scale\n", prw, prh); 879 break; 880 } 881 } 882 else 883 { 884 /* fprintf (stderr, "No rotation\n"); */ 885 fprintf (fd, "%f %f scale\n", prw, prh); 886 } 887 } 888 PSpage(fd, tif, w, h); 889 fprintf(fd, "end\n"); 890 fprintf(fd, "grestore\n"); 891 fprintf(fd, "showpage\n"); 892 } 893 if (generateEPSF) 894 break; 895 TIFFGetFieldDefaulted(tif, TIFFTAG_SUBFILETYPE, &subfiletype); 896 } while (((subfiletype & FILETYPE_PAGE) || printAll) && 897 TIFFReadDirectory(tif)); 898 899 return(npages); 900} 901 902static char DuplexPreamble[] = "\ 903%%BeginFeature: *Duplex True\n\ 904systemdict begin\n\ 905 /languagelevel where { pop languagelevel } { 1 } ifelse\n\ 906 2 ge { 1 dict dup /Duplex true put setpagedevice }\n\ 907 { statusdict /setduplex known { statusdict begin setduplex true end } if\n\ 908 } ifelse\n\ 909end\n\ 910%%EndFeature\n\ 911"; 912 913static char TumblePreamble[] = "\ 914%%BeginFeature: *Tumble True\n\ 915systemdict begin\n\ 916 /languagelevel where { pop languagelevel } { 1 } ifelse\n\ 917 2 ge { 1 dict dup /Tumble true put setpagedevice }\n\ 918 { statusdict /settumble known { statusdict begin true settumble end } if\n\ 919 } ifelse\n\ 920end\n\ 921%%EndFeature\n\ 922"; 923 924static char AvoidDeadZonePreamble[] = "\ 925gsave newpath clippath pathbbox grestore\n\ 926 4 2 roll 2 copy translate\n\ 927 exch 3 1 roll sub 3 1 roll sub exch\n\ 928 currentpagedevice /PageSize get aload pop\n\ 929 exch 3 1 roll div 3 1 roll div abs exch abs\n\ 930 2 copy gt { exch } if pop\n\ 931 dup 1 lt { dup scale } { pop } ifelse\n\ 932"; 933 934void 935PSHead(FILE *fd, TIFF *tif, uint32 w, uint32 h, 936 double pw, double ph, double ox, double oy) 937{ 938 time_t t; 939 940 (void) tif; (void) w; (void) h; 941 t = time(0); 942 fprintf(fd, "%%!PS-Adobe-3.0%s\n", generateEPSF ? " EPSF-3.0" : ""); 943 fprintf(fd, "%%%%Creator: tiff2ps\n"); 944 fprintf(fd, "%%%%Title: %s\n", filename); 945 fprintf(fd, "%%%%CreationDate: %s", ctime(&t)); 946 fprintf(fd, "%%%%DocumentData: Clean7Bit\n"); 947 fprintf(fd, "%%%%Origin: %ld %ld\n", (long) ox, (long) oy); 948 /* NB: should use PageBoundingBox */ 949 if (rotate && (rotation == 90 || rotation == 270)) 950 fprintf(fd, "%%%%BoundingBox: 0 0 %ld %ld\n", 951 (long) ceil(ph), (long) ceil(pw)); 952 else 953 fprintf(fd, "%%%%BoundingBox: 0 0 %ld %ld\n", 954 (long) ceil(pw), (long) ceil(ph)); 955 956 fprintf(fd, "%%%%LanguageLevel: %d\n", (level3 ? 3 : (level2 ? 2 : 1))); 957 fprintf(fd, "%%%%Pages: (atend)\n"); 958 fprintf(fd, "%%%%EndComments\n"); 959 fprintf(fd, "%%%%BeginSetup\n"); 960 if (PSduplex) 961 fprintf(fd, "%s", DuplexPreamble); 962 if (PStumble) 963 fprintf(fd, "%s", TumblePreamble); 964 if (PSavoiddeadzone && (level2 || level3)) 965 fprintf(fd, "%s", AvoidDeadZonePreamble); 966 fprintf(fd, "%%%%EndSetup\n"); 967} 968 969void 970PSTail(FILE *fd, int npages) 971{ 972 fprintf(fd, "%%%%Trailer\n"); 973 fprintf(fd, "%%%%Pages: %d\n", npages); 974 fprintf(fd, "%%%%EOF\n"); 975} 976 977static int 978checkcmap(TIFF* tif, int n, uint16* r, uint16* g, uint16* b) 979{ 980 (void) tif; 981 while (n-- > 0) 982 if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) 983 return (16); 984 TIFFWarning(filename, "Assuming 8-bit colormap"); 985 return (8); 986} 987 988static void 989PS_Lvl2colorspace(FILE* fd, TIFF* tif) 990{ 991 uint16 *rmap, *gmap, *bmap; 992 int i, num_colors; 993 const char * colorspace_p; 994 995 switch ( photometric ) 996 { 997 case PHOTOMETRIC_SEPARATED: 998 colorspace_p = "CMYK"; 999 break; 1000 1001 case PHOTOMETRIC_RGB: 1002 colorspace_p = "RGB"; 1003 break; 1004 1005 default: 1006 colorspace_p = "Gray"; 1007 } 1008 1009 /* 1010 * Set up PostScript Level 2 colorspace according to 1011 * section 4.8 in the PostScript refenence manual. 1012 */ 1013 fputs("% PostScript Level 2 only.\n", fd); 1014 if (photometric != PHOTOMETRIC_PALETTE) { 1015 if (photometric == PHOTOMETRIC_YCBCR) { 1016 /* MORE CODE HERE */ 1017 } 1018 fprintf(fd, "/Device%s setcolorspace\n", colorspace_p ); 1019 return; 1020 } 1021 1022 /* 1023 * Set up an indexed/palette colorspace 1024 */ 1025 num_colors = (1 << bitspersample); 1026 if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) { 1027 TIFFError(filename, 1028 "Palette image w/o \"Colormap\" tag"); 1029 return; 1030 } 1031 if (checkcmap(tif, num_colors, rmap, gmap, bmap) == 16) { 1032 /* 1033 * Convert colormap to 8-bits values. 1034 */ 1035#define CVT(x) (((x) * 255) / ((1L<<16)-1)) 1036 for (i = 0; i < num_colors; i++) { 1037 rmap[i] = CVT(rmap[i]); 1038 gmap[i] = CVT(gmap[i]); 1039 bmap[i] = CVT(bmap[i]); 1040 } 1041#undef CVT 1042 } 1043 fprintf(fd, "[ /Indexed /DeviceRGB %d", num_colors - 1); 1044 if (ascii85) { 1045 Ascii85Init(); 1046 fputs("\n<~", fd); 1047 ascii85breaklen -= 2; 1048 } else 1049 fputs(" <", fd); 1050 for (i = 0; i < num_colors; i++) { 1051 if (ascii85) { 1052 Ascii85Put((unsigned char)rmap[i], fd); 1053 Ascii85Put((unsigned char)gmap[i], fd); 1054 Ascii85Put((unsigned char)bmap[i], fd); 1055 } else { 1056 fputs((i % 8) ? " " : "\n ", fd); 1057 fprintf(fd, "%02x%02x%02x", 1058 rmap[i], gmap[i], bmap[i]); 1059 } 1060 } 1061 if (ascii85) 1062 Ascii85Flush(fd); 1063 else 1064 fputs(">\n", fd); 1065 fputs("] setcolorspace\n", fd); 1066} 1067 1068static int 1069PS_Lvl2ImageDict(FILE* fd, TIFF* tif, uint32 w, uint32 h) 1070{ 1071 int use_rawdata; 1072 uint32 tile_width, tile_height; 1073 uint16 predictor, minsamplevalue, maxsamplevalue; 1074 int repeat_count; 1075 char im_h[64], im_x[64], im_y[64]; 1076 char * imageOp = "image"; 1077 1078 if ( useImagemask && (bitspersample == 1) ) 1079 imageOp = "imagemask"; 1080 1081 (void)strcpy(im_x, "0"); 1082 (void)sprintf(im_y, "%lu", (long) h); 1083 (void)sprintf(im_h, "%lu", (long) h); 1084 tile_width = w; 1085 tile_height = h; 1086 if (TIFFIsTiled(tif)) { 1087 repeat_count = TIFFNumberOfTiles(tif); 1088 TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_width); 1089 TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_height); 1090 if (tile_width > w || tile_height > h || 1091 (w % tile_width) != 0 || (h % tile_height != 0)) { 1092 /* 1093 * The tiles does not fit image width and height. 1094 * Set up a clip rectangle for the image unit square. 1095 */ 1096 fputs("0 0 1 1 rectclip\n", fd); 1097 } 1098 if (tile_width < w) { 1099 fputs("/im_x 0 def\n", fd); 1100 (void)strcpy(im_x, "im_x neg"); 1101 } 1102 if (tile_height < h) { 1103 fputs("/im_y 0 def\n", fd); 1104 (void)sprintf(im_y, "%lu im_y sub", (unsigned long) h); 1105 } 1106 } else { 1107 repeat_count = tf_numberstrips; 1108 tile_height = tf_rowsperstrip; 1109 if (tile_height > h) 1110 tile_height = h; 1111 if (repeat_count > 1) { 1112 fputs("/im_y 0 def\n", fd); 1113 fprintf(fd, "/im_h %lu def\n", 1114 (unsigned long) tile_height); 1115 (void)strcpy(im_h, "im_h"); 1116 (void)sprintf(im_y, "%lu im_y sub", (unsigned long) h); 1117 } 1118 } 1119 1120 /* 1121 * Output start of exec block 1122 */ 1123 fputs("{ % exec\n", fd); 1124 1125 if (repeat_count > 1) 1126 fprintf(fd, "%d { %% repeat\n", repeat_count); 1127 1128 /* 1129 * Output filter options and image dictionary. 1130 */ 1131 if (ascii85) 1132 fputs(" /im_stream currentfile /ASCII85Decode filter def\n", 1133 fd); 1134 fputs(" <<\n", fd); 1135 fputs(" /ImageType 1\n", fd); 1136 fprintf(fd, " /Width %lu\n", (unsigned long) tile_width); 1137 /* 1138 * Workaround for some software that may crash when last strip 1139 * of image contains fewer number of scanlines than specified 1140 * by the `/Height' variable. So for stripped images with multiple 1141 * strips we will set `/Height' as `im_h', because one is 1142 * recalculated for each strip - including the (smaller) final strip. 1143 * For tiled images and images with only one strip `/Height' will 1144 * contain number of scanlines in tile (or image height in case of 1145 * one-stripped image). 1146 */ 1147 if (TIFFIsTiled(tif) || tf_numberstrips == 1) 1148 fprintf(fd, " /Height %lu\n", (unsigned long) tile_height); 1149 else 1150 fprintf(fd, " /Height im_h\n"); 1151 1152 if (planarconfiguration == PLANARCONFIG_SEPARATE && samplesperpixel > 1) 1153 fputs(" /MultipleDataSources true\n", fd); 1154 fprintf(fd, " /ImageMatrix [ %lu 0 0 %ld %s %s ]\n", 1155 (unsigned long) w, - (long)h, im_x, im_y); 1156 fprintf(fd, " /BitsPerComponent %d\n", bitspersample); 1157 fprintf(fd, " /Interpolate %s\n", interpolate ? "true" : "false"); 1158 1159 switch (samplesperpixel - extrasamples) { 1160 case 1: 1161 switch (photometric) { 1162 case PHOTOMETRIC_MINISBLACK: 1163 fputs(" /Decode [0 1]\n", fd); 1164 break; 1165 case PHOTOMETRIC_MINISWHITE: 1166 switch (compression) { 1167 case COMPRESSION_CCITTRLE: 1168 case COMPRESSION_CCITTRLEW: 1169 case COMPRESSION_CCITTFAX3: 1170 case COMPRESSION_CCITTFAX4: 1171 /* 1172 * Manage inverting with /Blackis1 flag 1173 * since there migth be uncompressed parts 1174 */ 1175 fputs(" /Decode [0 1]\n", fd); 1176 break; 1177 default: 1178 /* 1179 * ERROR... 1180 */ 1181 fputs(" /Decode [1 0]\n", fd); 1182 break; 1183 } 1184 break; 1185 case PHOTOMETRIC_PALETTE: 1186 TIFFGetFieldDefaulted(tif, TIFFTAG_MINSAMPLEVALUE, 1187 &minsamplevalue); 1188 TIFFGetFieldDefaulted(tif, TIFFTAG_MAXSAMPLEVALUE, 1189 &maxsamplevalue); 1190 fprintf(fd, " /Decode [%u %u]\n", 1191 minsamplevalue, maxsamplevalue); 1192 break; 1193 default: 1194 /* 1195 * ERROR ? 1196 */ 1197 fputs(" /Decode [0 1]\n", fd); 1198 break; 1199 } 1200 break; 1201 case 3: 1202 switch (photometric) { 1203 case PHOTOMETRIC_RGB: 1204 fputs(" /Decode [0 1 0 1 0 1]\n", fd); 1205 break; 1206 case PHOTOMETRIC_MINISWHITE: 1207 case PHOTOMETRIC_MINISBLACK: 1208 default: 1209 /* 1210 * ERROR?? 1211 */ 1212 fputs(" /Decode [0 1 0 1 0 1]\n", fd); 1213 break; 1214 } 1215 break; 1216 case 4: 1217 /* 1218 * ERROR?? 1219 */ 1220 fputs(" /Decode [0 1 0 1 0 1 0 1]\n", fd); 1221 break; 1222 } 1223 fputs(" /DataSource", fd); 1224 if (planarconfiguration == PLANARCONFIG_SEPARATE && 1225 samplesperpixel > 1) 1226 fputs(" [", fd); 1227 if (ascii85) 1228 fputs(" im_stream", fd); 1229 else 1230 fputs(" currentfile /ASCIIHexDecode filter", fd); 1231 1232 use_rawdata = TRUE; 1233 switch (compression) { 1234 case COMPRESSION_NONE: /* 1: uncompressed */ 1235 break; 1236 case COMPRESSION_CCITTRLE: /* 2: CCITT modified Huffman RLE */ 1237 case COMPRESSION_CCITTRLEW: /* 32771: #1 w/ word alignment */ 1238 case COMPRESSION_CCITTFAX3: /* 3: CCITT Group 3 fax encoding */ 1239 case COMPRESSION_CCITTFAX4: /* 4: CCITT Group 4 fax encoding */ 1240 fputs("\n\t<<\n", fd); 1241 if (compression == COMPRESSION_CCITTFAX3) { 1242 uint32 g3_options; 1243 1244 fputs("\t /EndOfLine true\n", fd); 1245 fputs("\t /EndOfBlock false\n", fd); 1246 if (!TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS, 1247 &g3_options)) 1248 g3_options = 0; 1249 if (g3_options & GROUP3OPT_2DENCODING) 1250 fprintf(fd, "\t /K %s\n", im_h); 1251 if (g3_options & GROUP3OPT_UNCOMPRESSED) 1252 fputs("\t /Uncompressed true\n", fd); 1253 if (g3_options & GROUP3OPT_FILLBITS) 1254 fputs("\t /EncodedByteAlign true\n", fd); 1255 } 1256 if (compression == COMPRESSION_CCITTFAX4) { 1257 uint32 g4_options; 1258 1259 fputs("\t /K -1\n", fd); 1260 TIFFGetFieldDefaulted(tif, TIFFTAG_GROUP4OPTIONS, 1261 &g4_options); 1262 if (g4_options & GROUP4OPT_UNCOMPRESSED) 1263 fputs("\t /Uncompressed true\n", fd); 1264 } 1265 if (!(tile_width == w && w == 1728U)) 1266 fprintf(fd, "\t /Columns %lu\n", 1267 (unsigned long) tile_width); 1268 fprintf(fd, "\t /Rows %s\n", im_h); 1269 if (compression == COMPRESSION_CCITTRLE || 1270 compression == COMPRESSION_CCITTRLEW) { 1271 fputs("\t /EncodedByteAlign true\n", fd); 1272 fputs("\t /EndOfBlock false\n", fd); 1273 } 1274 if (photometric == PHOTOMETRIC_MINISBLACK) 1275 fputs("\t /BlackIs1 true\n", fd); 1276 fprintf(fd, "\t>> /CCITTFaxDecode filter"); 1277 break; 1278 case COMPRESSION_LZW: /* 5: Lempel-Ziv & Welch */ 1279 TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor); 1280 if (predictor == 2) { 1281 fputs("\n\t<<\n", fd); 1282 fprintf(fd, "\t /Predictor %u\n", predictor); 1283 fprintf(fd, "\t /Columns %lu\n", 1284 (unsigned long) tile_width); 1285 fprintf(fd, "\t /Colors %u\n", samplesperpixel); 1286 fprintf(fd, "\t /BitsPerComponent %u\n", 1287 bitspersample); 1288 fputs("\t>>", fd); 1289 } 1290 fputs(" /LZWDecode filter", fd); 1291 break; 1292 case COMPRESSION_DEFLATE: /* 5: ZIP */ 1293 case COMPRESSION_ADOBE_DEFLATE: 1294 if ( level3 ) { 1295 TIFFGetFieldDefaulted(tif, TIFFTAG_PREDICTOR, &predictor); 1296 if (predictor > 1) { 1297 fprintf(fd, "\t %% PostScript Level 3 only."); 1298 fputs("\n\t<<\n", fd); 1299 fprintf(fd, "\t /Predictor %u\n", predictor); 1300 fprintf(fd, "\t /Columns %lu\n", 1301 (unsigned long) tile_width); 1302 fprintf(fd, "\t /Colors %u\n", samplesperpixel); 1303 fprintf(fd, "\t /BitsPerComponent %u\n", 1304 bitspersample); 1305 fputs("\t>>", fd); 1306 } 1307 fputs(" /FlateDecode filter", fd); 1308 } else { 1309 use_rawdata = FALSE ; 1310 } 1311 break; 1312 case COMPRESSION_PACKBITS: /* 32773: Macintosh RLE */ 1313 fputs(" /RunLengthDecode filter", fd); 1314 use_rawdata = TRUE; 1315 break; 1316 case COMPRESSION_OJPEG: /* 6: !6.0 JPEG */ 1317 case COMPRESSION_JPEG: /* 7: %JPEG DCT compression */ 1318#ifdef notdef 1319 /* 1320 * Code not tested yet 1321 */ 1322 fputs(" /DCTDecode filter", fd); 1323 use_rawdata = TRUE; 1324#else 1325 use_rawdata = FALSE; 1326#endif 1327 break; 1328 case COMPRESSION_NEXT: /* 32766: NeXT 2-bit RLE */ 1329 case COMPRESSION_THUNDERSCAN: /* 32809: ThunderScan RLE */ 1330 case COMPRESSION_PIXARFILM: /* 32908: Pixar companded 10bit LZW */ 1331 case COMPRESSION_JBIG: /* 34661: ISO JBIG */ 1332 use_rawdata = FALSE; 1333 break; 1334 case COMPRESSION_SGILOG: /* 34676: SGI LogL or LogLuv */ 1335 case COMPRESSION_SGILOG24: /* 34677: SGI 24-bit LogLuv */ 1336 use_rawdata = FALSE; 1337 break; 1338 default: 1339 /* 1340 * ERROR... 1341 */ 1342 use_rawdata = FALSE; 1343 break; 1344 } 1345 if (planarconfiguration == PLANARCONFIG_SEPARATE && 1346 samplesperpixel > 1) { 1347 uint16 i; 1348 1349 /* 1350 * NOTE: This code does not work yet... 1351 */ 1352 for (i = 1; i < samplesperpixel; i++) 1353 fputs(" dup", fd); 1354 fputs(" ]", fd); 1355 } 1356 1357 fprintf( fd, "\n >> %s\n", imageOp ); 1358 if (ascii85) 1359 fputs(" im_stream status { im_stream flushfile } if\n", fd); 1360 if (repeat_count > 1) { 1361 if (tile_width < w) { 1362 fprintf(fd, " /im_x im_x %lu add def\n", 1363 (unsigned long) tile_width); 1364 if (tile_height < h) { 1365 fprintf(fd, " im_x %lu ge {\n", 1366 (unsigned long) w); 1367 fputs(" /im_x 0 def\n", fd); 1368 fprintf(fd, " /im_y im_y %lu add def\n", 1369 (unsigned long) tile_height); 1370 fputs(" } if\n", fd); 1371 } 1372 } 1373 if (tile_height < h) { 1374 if (tile_width >= w) { 1375 fprintf(fd, " /im_y im_y %lu add def\n", 1376 (unsigned long) tile_height); 1377 if (!TIFFIsTiled(tif)) { 1378 fprintf(fd, " /im_h %lu im_y sub", 1379 (unsigned long) h); 1380 fprintf(fd, " dup %lu gt { pop", 1381 (unsigned long) tile_height); 1382 fprintf(fd, " %lu } if def\n", 1383 (unsigned long) tile_height); 1384 } 1385 } 1386 } 1387 fputs("} repeat\n", fd); 1388 } 1389 /* 1390 * End of exec function 1391 */ 1392 fputs("}\n", fd); 1393 1394 return(use_rawdata); 1395} 1396 1397/* Flip the byte order of buffers with 16 bit samples */ 1398static void 1399PS_FlipBytes(unsigned char* buf, int count) 1400{ 1401 int i; 1402 unsigned char temp; 1403 1404 if (count <= 0 || bitspersample <= 8) { 1405 return; 1406 } 1407 1408 count--; 1409 1410 for (i = 0; i < count; i += 2) { 1411 temp = buf[i]; 1412 buf[i] = buf[i + 1]; 1413 buf[i + 1] = temp; 1414 } 1415} 1416 1417#define MAXLINE 36 1418 1419int 1420PS_Lvl2page(FILE* fd, TIFF* tif, uint32 w, uint32 h) 1421{ 1422 uint16 fillorder; 1423 int use_rawdata, tiled_image, breaklen = MAXLINE; 1424 uint32 chunk_no, num_chunks, *bc; 1425 unsigned char *buf_data, *cp; 1426 tsize_t chunk_size, byte_count; 1427 1428#if defined( EXP_ASCII85ENCODER ) 1429 int ascii85_l; /* Length, in bytes, of ascii85_p[] data */ 1430 uint8 * ascii85_p = 0; /* Holds ASCII85 encoded data */ 1431#endif 1432 1433 PS_Lvl2colorspace(fd, tif); 1434 use_rawdata = PS_Lvl2ImageDict(fd, tif, w, h); 1435 1436/* See http://bugzilla.remotesensing.org/show_bug.cgi?id=80 */ 1437#ifdef ENABLE_BROKEN_BEGINENDDATA 1438 fputs("%%BeginData:\n", fd); 1439#endif 1440 fputs("exec\n", fd); 1441 1442 tiled_image = TIFFIsTiled(tif); 1443 if (tiled_image) { 1444 num_chunks = TIFFNumberOfTiles(tif); 1445 TIFFGetField(tif, TIFFTAG_TILEBYTECOUNTS, &bc); 1446 } else { 1447 num_chunks = TIFFNumberOfStrips(tif); 1448 TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc); 1449 } 1450 1451 if (use_rawdata) { 1452 chunk_size = (tsize_t) bc[0]; 1453 for (chunk_no = 1; chunk_no < num_chunks; chunk_no++) 1454 if ((tsize_t) bc[chunk_no] > chunk_size) 1455 chunk_size = (tsize_t) bc[chunk_no]; 1456 } else { 1457 if (tiled_image) 1458 chunk_size = TIFFTileSize(tif); 1459 else 1460 chunk_size = TIFFStripSize(tif); 1461 } 1462 buf_data = (unsigned char *)_TIFFmalloc(chunk_size); 1463 if (!buf_data) { 1464 TIFFError(filename, "Can't alloc %u bytes for %s.", 1465 chunk_size, tiled_image ? "tiles" : "strips"); 1466 return(FALSE); 1467 } 1468 1469#if defined( EXP_ASCII85ENCODER ) 1470 if ( ascii85 ) { 1471 /* 1472 * Allocate a buffer to hold the ASCII85 encoded data. Note 1473 * that it is allocated with sufficient room to hold the 1474 * encoded data (5*chunk_size/4) plus the EOD marker (+8) 1475 * and formatting line breaks. The line breaks are more 1476 * than taken care of by using 6*chunk_size/4 rather than 1477 * 5*chunk_size/4. 1478 */ 1479 1480 ascii85_p = _TIFFmalloc( (chunk_size+(chunk_size/2)) + 8 ); 1481 1482 if ( !ascii85_p ) { 1483 _TIFFfree( buf_data ); 1484 1485 TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." ); 1486 return ( FALSE ); 1487 } 1488 } 1489#endif 1490 1491 TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder); 1492 for (chunk_no = 0; chunk_no < num_chunks; chunk_no++) { 1493 if (ascii85) 1494 Ascii85Init(); 1495 else 1496 breaklen = MAXLINE; 1497 if (use_rawdata) { 1498 if (tiled_image) 1499 byte_count = TIFFReadRawTile(tif, chunk_no, 1500 buf_data, chunk_size); 1501 else 1502 byte_count = TIFFReadRawStrip(tif, chunk_no, 1503 buf_data, chunk_size); 1504 if (fillorder == FILLORDER_LSB2MSB) 1505 TIFFReverseBits(buf_data, byte_count); 1506 } else { 1507 if (tiled_image) 1508 byte_count = TIFFReadEncodedTile(tif, 1509 chunk_no, buf_data, 1510 chunk_size); 1511 else 1512 byte_count = TIFFReadEncodedStrip(tif, 1513 chunk_no, buf_data, 1514 chunk_size); 1515 } 1516 if (byte_count < 0) { 1517 TIFFError(filename, "Can't read %s %d.", 1518 tiled_image ? "tile" : "strip", chunk_no); 1519 if (ascii85) 1520 Ascii85Put('\0', fd); 1521 } 1522 /* 1523 * for 16 bits, the two bytes must be most significant 1524 * byte first 1525 */ 1526 if (bitspersample == 16 && !TIFFIsBigEndian(tif)) { 1527 PS_FlipBytes(buf_data, byte_count); 1528 } 1529 /* 1530 * For images with alpha, matte against a white background; 1531 * i.e. Cback * (1 - Aimage) where Cback = 1. We will fill the 1532 * lower part of the buffer with the modified values. 1533 * 1534 * XXX: needs better solution 1535 */ 1536 if (alpha) { 1537 int adjust, i, j = 0; 1538 int ncomps = samplesperpixel - extrasamples; 1539 for (i = 0; i < byte_count; i+=samplesperpixel) { 1540 adjust = 255 - buf_data[i + ncomps]; 1541 switch (ncomps) { 1542 case 1: 1543 buf_data[j++] = buf_data[i] + adjust; 1544 break; 1545 case 2: 1546 buf_data[j++] = buf_data[i] + adjust; 1547 buf_data[j++] = buf_data[i+1] + adjust; 1548 break; 1549 case 3: 1550 buf_data[j++] = buf_data[i] + adjust; 1551 buf_data[j++] = buf_data[i+1] + adjust; 1552 buf_data[j++] = buf_data[i+2] + adjust; 1553 break; 1554 } 1555 } 1556 byte_count -= j; 1557 } 1558 1559 if (ascii85) { 1560#if defined( EXP_ASCII85ENCODER ) 1561 ascii85_l = Ascii85EncodeBlock(ascii85_p, 1, buf_data, byte_count ); 1562 1563 if ( ascii85_l > 0 ) 1564 fwrite( ascii85_p, ascii85_l, 1, fd ); 1565#else 1566 for (cp = buf_data; byte_count > 0; byte_count--) 1567 Ascii85Put(*cp++, fd); 1568#endif 1569 } 1570 else 1571 { 1572 for (cp = buf_data; byte_count > 0; byte_count--) { 1573 putc(hex[((*cp)>>4)&0xf], fd); 1574 putc(hex[(*cp)&0xf], fd); 1575 cp++; 1576 1577 if (--breaklen <= 0) { 1578 putc('\n', fd); 1579 breaklen = MAXLINE; 1580 } 1581 } 1582 } 1583 1584 if ( !ascii85 ) { 1585 if ( level2 || level3 ) 1586 putc( '>', fd ); 1587 putc('\n', fd); 1588 } 1589#if !defined( EXP_ASCII85ENCODER ) 1590 else 1591 Ascii85Flush(fd); 1592#endif 1593 } 1594 1595#if defined( EXP_ASCII85ENCODER ) 1596 if ( ascii85_p ) 1597 _TIFFfree( ascii85_p ); 1598#endif 1599 1600 _TIFFfree(buf_data); 1601#ifdef ENABLE_BROKEN_BEGINENDDATA 1602 fputs("%%EndData\n", fd); 1603#endif 1604 return(TRUE); 1605} 1606 1607void 1608PSpage(FILE* fd, TIFF* tif, uint32 w, uint32 h) 1609{ 1610 char * imageOp = "image"; 1611 1612 if ( useImagemask && (bitspersample == 1) ) 1613 imageOp = "imagemask"; 1614 1615 if ((level2 || level3) && PS_Lvl2page(fd, tif, w, h)) 1616 return; 1617 ps_bytesperrow = tf_bytesperrow - (extrasamples * bitspersample / 8)*w; 1618 switch (photometric) { 1619 case PHOTOMETRIC_RGB: 1620 if (planarconfiguration == PLANARCONFIG_CONTIG) { 1621 fprintf(fd, "%s", RGBcolorimage); 1622 PSColorContigPreamble(fd, w, h, 3); 1623 PSDataColorContig(fd, tif, w, h, 3); 1624 } else { 1625 PSColorSeparatePreamble(fd, w, h, 3); 1626 PSDataColorSeparate(fd, tif, w, h, 3); 1627 } 1628 break; 1629 case PHOTOMETRIC_SEPARATED: 1630 /* XXX should emit CMYKcolorimage */ 1631 if (planarconfiguration == PLANARCONFIG_CONTIG) { 1632 PSColorContigPreamble(fd, w, h, 4); 1633 PSDataColorContig(fd, tif, w, h, 4); 1634 } else { 1635 PSColorSeparatePreamble(fd, w, h, 4); 1636 PSDataColorSeparate(fd, tif, w, h, 4); 1637 } 1638 break; 1639 case PHOTOMETRIC_PALETTE: 1640 fprintf(fd, "%s", RGBcolorimage); 1641 PhotoshopBanner(fd, w, h, 1, 3, "false 3 colorimage"); 1642 fprintf(fd, "/scanLine %ld string def\n", 1643 (long) ps_bytesperrow * 3L); 1644 fprintf(fd, "%lu %lu 8\n", 1645 (unsigned long) w, (unsigned long) h); 1646 fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n", 1647 (unsigned long) w, (unsigned long) h, (unsigned long) h); 1648 fprintf(fd, "{currentfile scanLine readhexstring pop} bind\n"); 1649 fprintf(fd, "false 3 colorimage\n"); 1650 PSDataPalette(fd, tif, w, h); 1651 break; 1652 case PHOTOMETRIC_MINISBLACK: 1653 case PHOTOMETRIC_MINISWHITE: 1654 PhotoshopBanner(fd, w, h, 1, 1, imageOp); 1655 fprintf(fd, "/scanLine %ld string def\n", 1656 (long) ps_bytesperrow); 1657 fprintf(fd, "%lu %lu %d\n", 1658 (unsigned long) w, (unsigned long) h, bitspersample); 1659 fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n", 1660 (unsigned long) w, (unsigned long) h, (unsigned long) h); 1661 fprintf(fd, 1662 "{currentfile scanLine readhexstring pop} bind\n"); 1663 fprintf(fd, "%s\n", imageOp); 1664 PSDataBW(fd, tif, w, h); 1665 break; 1666 } 1667 putc('\n', fd); 1668} 1669 1670void 1671PSColorContigPreamble(FILE* fd, uint32 w, uint32 h, int nc) 1672{ 1673 ps_bytesperrow = nc * (tf_bytesperrow / samplesperpixel); 1674 PhotoshopBanner(fd, w, h, 1, nc, "false %d colorimage"); 1675 fprintf(fd, "/line %ld string def\n", (long) ps_bytesperrow); 1676 fprintf(fd, "%lu %lu %d\n", 1677 (unsigned long) w, (unsigned long) h, bitspersample); 1678 fprintf(fd, "[%lu 0 0 -%lu 0 %lu]\n", 1679 (unsigned long) w, (unsigned long) h, (unsigned long) h); 1680 fprintf(fd, "{currentfile line readhexstring pop} bind\n"); 1681 fprintf(fd, "false %d colorimage\n", nc); 1682} 1683 1684void 1685PSColorSeparatePreamble(FILE* fd, uint32 w, uint32 h, int nc) 1686{ 1687 int i; 1688 1689 PhotoshopBanner(fd, w, h, ps_bytesperrow, nc, "true %d colorimage"); 1690 for (i = 0; i < nc; i++) 1691 fprintf(fd, "/line%d %ld string def\n", 1692 i, (long) ps_bytesperrow); 1693 fprintf(fd, "%lu %lu %d\n", 1694 (unsigned long) w, (unsigned long) h, bitspersample); 1695 fprintf(fd, "[%lu 0 0 -%lu 0 %lu] \n", 1696 (unsigned long) w, (unsigned long) h, (unsigned long) h); 1697 for (i = 0; i < nc; i++) 1698 fprintf(fd, "{currentfile line%d readhexstring pop}bind\n", i); 1699 fprintf(fd, "true %d colorimage\n", nc); 1700} 1701 1702#define DOBREAK(len, howmany, fd) \ 1703 if (((len) -= (howmany)) <= 0) { \ 1704 putc('\n', fd); \ 1705 (len) = MAXLINE-(howmany); \ 1706 } 1707#define PUTHEX(c,fd) putc(hex[((c)>>4)&0xf],fd); putc(hex[(c)&0xf],fd) 1708 1709void 1710PSDataColorContig(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc) 1711{ 1712 uint32 row; 1713 int breaklen = MAXLINE, cc, es = samplesperpixel - nc; 1714 unsigned char *tf_buf; 1715 unsigned char *cp, c; 1716 1717 (void) w; 1718 tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow); 1719 if (tf_buf == NULL) { 1720 TIFFError(filename, "No space for scanline buffer"); 1721 return; 1722 } 1723 for (row = 0; row < h; row++) { 1724 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0) 1725 break; 1726 cp = tf_buf; 1727 /* 1728 * for 16 bits, the two bytes must be most significant 1729 * byte first 1730 */ 1731 if (bitspersample == 16 && !HOST_BIGENDIAN) { 1732 PS_FlipBytes(cp, tf_bytesperrow); 1733 } 1734 if (alpha) { 1735 int adjust; 1736 cc = 0; 1737 for (; cc < tf_bytesperrow; cc += samplesperpixel) { 1738 DOBREAK(breaklen, nc, fd); 1739 /* 1740 * For images with alpha, matte against 1741 * a white background; i.e. 1742 * Cback * (1 - Aimage) 1743 * where Cback = 1. 1744 */ 1745 adjust = 255 - cp[nc]; 1746 switch (nc) { 1747 case 4: c = *cp++ + adjust; PUTHEX(c,fd); 1748 case 3: c = *cp++ + adjust; PUTHEX(c,fd); 1749 case 2: c = *cp++ + adjust; PUTHEX(c,fd); 1750 case 1: c = *cp++ + adjust; PUTHEX(c,fd); 1751 } 1752 cp += es; 1753 } 1754 } else { 1755 cc = 0; 1756 for (; cc < tf_bytesperrow; cc += samplesperpixel) { 1757 DOBREAK(breaklen, nc, fd); 1758 switch (nc) { 1759 case 4: c = *cp++; PUTHEX(c,fd); 1760 case 3: c = *cp++; PUTHEX(c,fd); 1761 case 2: c = *cp++; PUTHEX(c,fd); 1762 case 1: c = *cp++; PUTHEX(c,fd); 1763 } 1764 cp += es; 1765 } 1766 } 1767 } 1768 _TIFFfree((char *) tf_buf); 1769} 1770 1771void 1772PSDataColorSeparate(FILE* fd, TIFF* tif, uint32 w, uint32 h, int nc) 1773{ 1774 uint32 row; 1775 int breaklen = MAXLINE, cc; 1776 tsample_t s, maxs; 1777 unsigned char *tf_buf; 1778 unsigned char *cp, c; 1779 1780 (void) w; 1781 tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow); 1782 if (tf_buf == NULL) { 1783 TIFFError(filename, "No space for scanline buffer"); 1784 return; 1785 } 1786 maxs = (samplesperpixel > nc ? nc : samplesperpixel); 1787 for (row = 0; row < h; row++) { 1788 for (s = 0; s < maxs; s++) { 1789 if (TIFFReadScanline(tif, tf_buf, row, s) < 0) 1790 break; 1791 for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) { 1792 DOBREAK(breaklen, 1, fd); 1793 c = *cp++; 1794 PUTHEX(c,fd); 1795 } 1796 } 1797 } 1798 _TIFFfree((char *) tf_buf); 1799} 1800 1801#define PUTRGBHEX(c,fd) \ 1802 PUTHEX(rmap[c],fd); PUTHEX(gmap[c],fd); PUTHEX(bmap[c],fd) 1803 1804void 1805PSDataPalette(FILE* fd, TIFF* tif, uint32 w, uint32 h) 1806{ 1807 uint16 *rmap, *gmap, *bmap; 1808 uint32 row; 1809 int breaklen = MAXLINE, cc, nc; 1810 unsigned char *tf_buf; 1811 unsigned char *cp, c; 1812 1813 (void) w; 1814 if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) { 1815 TIFFError(filename, "Palette image w/o \"Colormap\" tag"); 1816 return; 1817 } 1818 switch (bitspersample) { 1819 case 8: case 4: case 2: case 1: 1820 break; 1821 default: 1822 TIFFError(filename, "Depth %d not supported", bitspersample); 1823 return; 1824 } 1825 nc = 3 * (8 / bitspersample); 1826 tf_buf = (unsigned char *) _TIFFmalloc(tf_bytesperrow); 1827 if (tf_buf == NULL) { 1828 TIFFError(filename, "No space for scanline buffer"); 1829 return; 1830 } 1831 if (checkcmap(tif, 1<<bitspersample, rmap, gmap, bmap) == 16) { 1832 int i; 1833#define CVT(x) ((unsigned short) (((x) * 255) / ((1U<<16)-1))) 1834 for (i = (1<<bitspersample)-1; i >= 0; i--) { 1835 rmap[i] = CVT(rmap[i]); 1836 gmap[i] = CVT(gmap[i]); 1837 bmap[i] = CVT(bmap[i]); 1838 } 1839#undef CVT 1840 } 1841 for (row = 0; row < h; row++) { 1842 if (TIFFReadScanline(tif, tf_buf, row, 0) < 0) 1843 break; 1844 for (cp = tf_buf, cc = 0; cc < tf_bytesperrow; cc++) { 1845 DOBREAK(breaklen, nc, fd); 1846 switch (bitspersample) { 1847 case 8: 1848 c = *cp++; PUTRGBHEX(c, fd); 1849 break; 1850 case 4: 1851 c = *cp++; PUTRGBHEX(c&0xf, fd); 1852 c >>= 4; PUTRGBHEX(c, fd); 1853 break; 1854 case 2: 1855 c = *cp++; PUTRGBHEX(c&0x3, fd); 1856 c >>= 2; PUTRGBHEX(c&0x3, fd); 1857 c >>= 2; PUTRGBHEX(c&0x3, fd); 1858 c >>= 2; PUTRGBHEX(c, fd); 1859 break; 1860 case 1: 1861 c = *cp++; PUTRGBHEX(c&0x1, fd); 1862 c >>= 1; PUTRGBHEX(c&0x1, fd); 1863 c >>= 1; PUTRGBHEX(c&0x1, fd); 1864 c >>= 1; PUTRGBHEX(c&0x1, fd); 1865 c >>= 1; PUTRGBHEX(c&0x1, fd); 1866 c >>= 1; PUTRGBHEX(c&0x1, fd); 1867 c >>= 1; PUTRGBHEX(c&0x1, fd); 1868 c >>= 1; PUTRGBHEX(c, fd); 1869 break; 1870 } 1871 } 1872 } 1873 _TIFFfree((char *) tf_buf); 1874} 1875 1876void 1877PSDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h) 1878{ 1879 int breaklen = MAXLINE; 1880 unsigned char* tf_buf; 1881 unsigned char* cp; 1882 tsize_t stripsize = TIFFStripSize(tif); 1883 tstrip_t s; 1884 1885#if defined( EXP_ASCII85ENCODER ) 1886 int ascii85_l; /* Length, in bytes, of ascii85_p[] data */ 1887 uint8 *ascii85_p = 0; /* Holds ASCII85 encoded data */ 1888#endif 1889 1890 (void) w; (void) h; 1891 tf_buf = (unsigned char *) _TIFFmalloc(stripsize); 1892 memset(tf_buf, 0, stripsize); 1893 if (tf_buf == NULL) { 1894 TIFFError(filename, "No space for scanline buffer"); 1895 return; 1896 } 1897 1898#if defined( EXP_ASCII85ENCODER ) 1899 if ( ascii85 ) { 1900 /* 1901 * Allocate a buffer to hold the ASCII85 encoded data. Note 1902 * that it is allocated with sufficient room to hold the 1903 * encoded data (5*stripsize/4) plus the EOD marker (+8) 1904 * and formatting line breaks. The line breaks are more 1905 * than taken care of by using 6*stripsize/4 rather than 1906 * 5*stripsize/4. 1907 */ 1908 1909 ascii85_p = _TIFFmalloc( (stripsize+(stripsize/2)) + 8 ); 1910 1911 if ( !ascii85_p ) { 1912 _TIFFfree( tf_buf ); 1913 1914 TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." ); 1915 return; 1916 } 1917 } 1918#endif 1919 1920 if (ascii85) 1921 Ascii85Init(); 1922 1923 for (s = 0; s < TIFFNumberOfStrips(tif); s++) { 1924 int cc = TIFFReadEncodedStrip(tif, s, tf_buf, stripsize); 1925 if (cc < 0) { 1926 TIFFError(filename, "Can't read strip"); 1927 break; 1928 } 1929 cp = tf_buf; 1930 if (photometric == PHOTOMETRIC_MINISWHITE) { 1931 for (cp += cc; --cp >= tf_buf;) 1932 *cp = ~*cp; 1933 cp++; 1934 } 1935 /* 1936 * for 16 bits, the two bytes must be most significant 1937 * byte first 1938 */ 1939 if (bitspersample == 16 && !HOST_BIGENDIAN) { 1940 PS_FlipBytes(cp, cc); 1941 } 1942 if (ascii85) { 1943#if defined( EXP_ASCII85ENCODER ) 1944 if (alpha) { 1945 int adjust, i; 1946 for (i = 0; i < cc; i+=2) { 1947 adjust = 255 - cp[i + 1]; 1948 cp[i / 2] = cp[i] + adjust; 1949 } 1950 cc /= 2; 1951 } 1952 1953 ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, cp, cc ); 1954 1955 if ( ascii85_l > 0 ) 1956 fwrite( ascii85_p, ascii85_l, 1, fd ); 1957#else 1958 while (cc-- > 0) 1959 Ascii85Put(*cp++, fd); 1960#endif /* EXP_ASCII85_ENCODER */ 1961 } else { 1962 unsigned char c; 1963 1964 if (alpha) { 1965 int adjust; 1966 while (cc-- > 0) { 1967 DOBREAK(breaklen, 1, fd); 1968 /* 1969 * For images with alpha, matte against 1970 * a white background; i.e. 1971 * Cback * (1 - Aimage) 1972 * where Cback = 1. 1973 */ 1974 adjust = 255 - cp[1]; 1975 c = *cp++ + adjust; PUTHEX(c,fd); 1976 cp++, cc--; 1977 } 1978 } else { 1979 while (cc-- > 0) { 1980 c = *cp++; 1981 DOBREAK(breaklen, 1, fd); 1982 PUTHEX(c, fd); 1983 } 1984 } 1985 } 1986 } 1987 1988 if ( !ascii85 ) 1989 { 1990 if ( level2 || level3) 1991 fputs(">\n", fd); 1992 } 1993#if !defined( EXP_ASCII85ENCODER ) 1994 else 1995 Ascii85Flush(fd); 1996#else 1997 if ( ascii85_p ) 1998 _TIFFfree( ascii85_p ); 1999#endif 2000 2001 _TIFFfree(tf_buf); 2002} 2003 2004void 2005PSRawDataBW(FILE* fd, TIFF* tif, uint32 w, uint32 h) 2006{ 2007 uint32 *bc; 2008 uint32 bufsize; 2009 int breaklen = MAXLINE, cc; 2010 uint16 fillorder; 2011 unsigned char *tf_buf; 2012 unsigned char *cp, c; 2013 tstrip_t s; 2014 2015#if defined( EXP_ASCII85ENCODER ) 2016 int ascii85_l; /* Length, in bytes, of ascii85_p[] data */ 2017 uint8 * ascii85_p = 0; /* Holds ASCII85 encoded data */ 2018#endif 2019 2020 (void) w; (void) h; 2021 TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder); 2022 TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bc); 2023 2024 /* 2025 * Find largest strip: 2026 */ 2027 2028 bufsize = bc[0]; 2029 2030 for ( s = 0; ++s < (tstrip_t)tf_numberstrips; ) { 2031 if ( bc[s] > bufsize ) 2032 bufsize = bc[s]; 2033 } 2034 2035 tf_buf = (unsigned char*) _TIFFmalloc(bufsize); 2036 if (tf_buf == NULL) { 2037 TIFFError(filename, "No space for strip buffer"); 2038 return; 2039 } 2040 2041#if defined( EXP_ASCII85ENCODER ) 2042 if ( ascii85 ) { 2043 /* 2044 * Allocate a buffer to hold the ASCII85 encoded data. Note 2045 * that it is allocated with sufficient room to hold the 2046 * encoded data (5*bufsize/4) plus the EOD marker (+8) 2047 * and formatting line breaks. The line breaks are more 2048 * than taken care of by using 6*bufsize/4 rather than 2049 * 5*bufsize/4. 2050 */ 2051 2052 ascii85_p = _TIFFmalloc( (bufsize+(bufsize/2)) + 8 ); 2053 2054 if ( !ascii85_p ) { 2055 _TIFFfree( tf_buf ); 2056 2057 TIFFError( filename, "Cannot allocate ASCII85 encoding buffer." ); 2058 return; 2059 } 2060 } 2061#endif 2062 2063 for (s = 0; s < (tstrip_t) tf_numberstrips; s++) { 2064 cc = TIFFReadRawStrip(tif, s, tf_buf, bc[s]); 2065 if (cc < 0) { 2066 TIFFError(filename, "Can't read strip"); 2067 break; 2068 } 2069 if (fillorder == FILLORDER_LSB2MSB) 2070 TIFFReverseBits(tf_buf, cc); 2071 if (!ascii85) { 2072 for (cp = tf_buf; cc > 0; cc--) { 2073 DOBREAK(breaklen, 1, fd); 2074 c = *cp++; 2075 PUTHEX(c, fd); 2076 } 2077 fputs(">\n", fd); 2078 breaklen = MAXLINE; 2079 } else { 2080 Ascii85Init(); 2081#if defined( EXP_ASCII85ENCODER ) 2082 ascii85_l = Ascii85EncodeBlock( ascii85_p, 1, tf_buf, cc ); 2083 2084 if ( ascii85_l > 0 ) 2085 fwrite( ascii85_p, ascii85_l, 1, fd ); 2086#else 2087 for (cp = tf_buf; cc > 0; cc--) 2088 Ascii85Put(*cp++, fd); 2089 Ascii85Flush(fd); 2090#endif /* EXP_ASCII85ENCODER */ 2091 } 2092 } 2093 _TIFFfree((char *) tf_buf); 2094 2095#if defined( EXP_ASCII85ENCODER ) 2096 if ( ascii85_p ) 2097 _TIFFfree( ascii85_p ); 2098#endif 2099} 2100 2101void 2102Ascii85Init(void) 2103{ 2104 ascii85breaklen = 2*MAXLINE; 2105 ascii85count = 0; 2106} 2107 2108static char* 2109Ascii85Encode(unsigned char* raw) 2110{ 2111 static char encoded[6]; 2112 uint32 word; 2113 2114 word = (((raw[0]<<8)+raw[1])<<16) + (raw[2]<<8) + raw[3]; 2115 if (word != 0L) { 2116 uint32 q; 2117 uint16 w1; 2118 2119 q = word / (85L*85*85*85); /* actually only a byte */ 2120 encoded[0] = (char) (q + '!'); 2121 2122 word -= q * (85L*85*85*85); q = word / (85L*85*85); 2123 encoded[1] = (char) (q + '!'); 2124 2125 word -= q * (85L*85*85); q = word / (85*85); 2126 encoded[2] = (char) (q + '!'); 2127 2128 w1 = (uint16) (word - q*(85L*85)); 2129 encoded[3] = (char) ((w1 / 85) + '!'); 2130 encoded[4] = (char) ((w1 % 85) + '!'); 2131 encoded[5] = '\0'; 2132 } else 2133 encoded[0] = 'z', encoded[1] = '\0'; 2134 return (encoded); 2135} 2136 2137void 2138Ascii85Put(unsigned char code, FILE* fd) 2139{ 2140 ascii85buf[ascii85count++] = code; 2141 if (ascii85count >= 4) { 2142 unsigned char* p; 2143 int n; 2144 2145 for (n = ascii85count, p = ascii85buf; n >= 4; n -= 4, p += 4) { 2146 char* cp; 2147 for (cp = Ascii85Encode(p); *cp; cp++) { 2148 putc(*cp, fd); 2149 if (--ascii85breaklen == 0) { 2150 putc('\n', fd); 2151 ascii85breaklen = 2*MAXLINE; 2152 } 2153 } 2154 } 2155 _TIFFmemcpy(ascii85buf, p, n); 2156 ascii85count = n; 2157 } 2158} 2159 2160void 2161Ascii85Flush(FILE* fd) 2162{ 2163 if (ascii85count > 0) { 2164 char* res; 2165 _TIFFmemset(&ascii85buf[ascii85count], 0, 3); 2166 res = Ascii85Encode(ascii85buf); 2167 fwrite(res[0] == 'z' ? "!!!!" : res, ascii85count + 1, 1, fd); 2168 } 2169 fputs("~>\n", fd); 2170} 2171#if defined( EXP_ASCII85ENCODER) 2172 2173#define A85BREAKCNTR ascii85breaklen 2174#define A85BREAKLEN (2*MAXLINE) 2175 2176/***************************************************************************** 2177* 2178* Name: Ascii85EncodeBlock( ascii85_p, f_eod, raw_p, raw_l ) 2179* 2180* Description: This routine will encode the raw data in the buffer described 2181* by raw_p and raw_l into ASCII85 format and store the encoding 2182* in the buffer given by ascii85_p. 2183* 2184* Parameters: ascii85_p - A buffer supplied by the caller which will 2185* contain the encoded ASCII85 data. 2186* f_eod - Flag: Nz means to end the encoded buffer with 2187* an End-Of-Data marker. 2188* raw_p - Pointer to the buffer of data to be encoded 2189* raw_l - Number of bytes in raw_p[] to be encoded 2190* 2191* Returns: (int) < 0 Error, see errno 2192* >= 0 Number of bytes written to ascii85_p[]. 2193* 2194* Notes: An external variable given by A85BREAKCNTR is used to 2195* determine when to insert newline characters into the 2196* encoded data. As each byte is placed into ascii85_p this 2197* external is decremented. If the variable is decrement to 2198* or past zero then a newline is inserted into ascii85_p 2199* and the A85BREAKCNTR is then reset to A85BREAKLEN. 2200* Note: for efficiency reasons the A85BREAKCNTR variable 2201* is not actually checked on *every* character 2202* placed into ascii85_p but often only for every 2203* 5 characters. 2204* 2205* THE CALLER IS RESPONSIBLE FOR ENSURING THAT ASCII85_P[] IS 2206* SUFFICIENTLY LARGE TO THE ENCODED DATA! 2207* You will need at least 5 * (raw_l/4) bytes plus space for 2208* newline characters and space for an EOD marker (if 2209* requested). A safe calculation is to use 6*(raw_l/4) + 8 2210* to size ascii85_p. 2211* 2212*****************************************************************************/ 2213 2214int Ascii85EncodeBlock( uint8 * ascii85_p, unsigned f_eod, const uint8 * raw_p, int raw_l ) 2215 2216{ 2217 char ascii85[5]; /* Encoded 5 tuple */ 2218 int ascii85_l; /* Number of bytes written to ascii85_p[] */ 2219 int rc; /* Return code */ 2220 uint32 val32; /* Unencoded 4 tuple */ 2221 2222 ascii85_l = 0; /* Nothing written yet */ 2223 2224 if ( raw_p ) 2225 { 2226 --raw_p; /* Prepare for pre-increment fetches */ 2227 2228 for ( ; raw_l > 3; raw_l -= 4 ) 2229 { 2230 val32 = *(++raw_p) << 24; 2231 val32 += *(++raw_p) << 16; 2232 val32 += *(++raw_p) << 8; 2233 val32 += *(++raw_p); 2234 2235 if ( val32 == 0 ) /* Special case */ 2236 { 2237 ascii85_p[ascii85_l] = 'z'; 2238 rc = 1; 2239 } 2240 2241 else 2242 { 2243 ascii85[4] = (char) ((val32 % 85) + 33); 2244 val32 /= 85; 2245 2246 ascii85[3] = (char) ((val32 % 85) + 33); 2247 val32 /= 85; 2248 2249 ascii85[2] = (char) ((val32 % 85) + 33); 2250 val32 /= 85; 2251 2252 ascii85[1] = (char) ((val32 % 85) + 33); 2253 ascii85[0] = (char) ((val32 / 85) + 33); 2254 2255 _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, sizeof(ascii85) ); 2256 rc = sizeof(ascii85); 2257 } 2258 2259 ascii85_l += rc; 2260 2261 if ( (A85BREAKCNTR -= rc) <= 0 ) 2262 { 2263 ascii85_p[ascii85_l] = '\n'; 2264 ++ascii85_l; 2265 A85BREAKCNTR = A85BREAKLEN; 2266 } 2267 } 2268 2269 /* 2270 * Output any straggler bytes: 2271 */ 2272 2273 if ( raw_l > 0 ) 2274 { 2275 int len; /* Output this many bytes */ 2276 2277 len = raw_l + 1; 2278 val32 = *++raw_p << 24; /* Prime the pump */ 2279 2280 if ( --raw_l > 0 ) val32 += *(++raw_p) << 16; 2281 if ( --raw_l > 0 ) val32 += *(++raw_p) << 8; 2282 2283 val32 /= 85; 2284 2285 ascii85[3] = (char) ((val32 % 85) + 33); 2286 val32 /= 85; 2287 2288 ascii85[2] = (char) ((val32 % 85) + 33); 2289 val32 /= 85; 2290 2291 ascii85[1] = (char) ((val32 % 85) + 33); 2292 ascii85[0] = (char) ((val32 / 85) + 33); 2293 2294 _TIFFmemcpy( &ascii85_p[ascii85_l], ascii85, len ); 2295 ascii85_l += len; 2296 } 2297 } 2298 2299 /* 2300 * If requested add an ASCII85 End Of Data marker: 2301 */ 2302 2303 if ( f_eod ) 2304 { 2305 ascii85_p[ascii85_l++] = '~'; 2306 ascii85_p[ascii85_l++] = '>'; 2307 ascii85_p[ascii85_l++] = '\n'; 2308 } 2309 2310 return ( ascii85_l ); 2311 2312} /* Ascii85EncodeBlock() */ 2313 2314#endif /* EXP_ASCII85ENCODER */ 2315 2316 2317char* stuff[] = { 2318"usage: tiff2ps [options] input.tif ...", 2319"where options are:", 2320" -1 generate PostScript Level 1 (default)", 2321" -2 generate PostScript Level 2", 2322" -3 generate PostScript Level 3", 2323" -8 disable use of ASCII85 encoding with PostScript Level 2/3", 2324" -a convert all directories in file (default is first)", 2325" -b # set the bottom margin to # inches", 2326" -c center image (-b and -l still add to this)", 2327" -d # convert directory number #", 2328" -D enable duplex printing (two pages per sheet of paper)", 2329" -e generate Encapsulated PostScript (EPS) (implies -z)", 2330" -h # assume printed page height is # inches (default 11)", 2331" -w # assume printed page width is # inches (default 8.5)", 2332" -H # split image if height is more than # inches", 2333" -W # split image if width is more than # inches", 2334" -L # overLap split images by # inches", 2335" -i # enable/disable (Nz/0) pixel interpolation (default: enable)", 2336" -l # set the left margin to # inches", 2337" -m use \"imagemask\" operator instead of \"image\"", 2338" -o # convert directory at file offset #", 2339" -O file write PostScript to file instead of standard output", 2340" -p generate regular PostScript", 2341" -r # or auto rotate by 90, 180, 270 degrees or auto", 2342" -s generate PostScript for a single image", 2343" -T print pages for top edge binding", 2344" -x override resolution units as centimeters", 2345" -y override resolution units as inches", 2346" -z enable printing in the deadzone (only for PostScript Level 2/3)", 2347NULL 2348}; 2349 2350static void 2351usage(int code) 2352{ 2353 char buf[BUFSIZ]; 2354 int i; 2355 2356 setbuf(stderr, buf); 2357 fprintf(stderr, "%s\n\n", TIFFGetVersion()); 2358 for (i = 0; stuff[i] != NULL; i++) 2359 fprintf(stderr, "%s\n", stuff[i]); 2360 exit(code); 2361} 2362 2363/* vim: set ts=8 sts=8 sw=8 noet: */ 2364/* 2365 * Local Variables: 2366 * mode: c 2367 * c-basic-offset: 8 2368 * fill-column: 78 2369 * End: 2370 */ 2371