]> granicus.if.org Git - imagemagick/blob - coders/ps3.c
(no commit message)
[imagemagick] / coders / ps3.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            PPPP   SSSSS  33333                              %
7 %                            P   P  SS        33                              %
8 %                            PPPP    SSS    333                               %
9 %                            P         SS     33                              %
10 %                            P      SSSSS  33333                              %
11 %                                                                             %
12 %                                                                             %
13 %                     Write Postscript Level III Format                       %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                John Cristy                                  %
17 %                              Lars Ruben Skyum                               %
18 %                                 July 1992                                   %
19 %                                                                             %
20 %                                                                             %
21 %  Copyright 1999-2009 ImageMagick Studio LLC, a non-profit organization      %
22 %  dedicated to making software imaging solutions freely available.           %
23 %                                                                             %
24 %  You may not use this file except in compliance with the License.  You may  %
25 %  obtain a copy of the License at                                            %
26 %                                                                             %
27 %    http://www.imagemagick.org/script/license.php                            %
28 %                                                                             %
29 %  Unless required by applicable law or agreed to in writing, software        %
30 %  distributed under the License is distributed on an "AS IS" BASIS,          %
31 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
32 %  See the License for the specific language governing permissions and        %
33 %  limitations under the License.                                             %
34 %                                                                             %
35 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36 %
37 %
38 */
39 \f
40 /*
41   Include declarations.
42 */
43 #include "magick/studio.h"
44 #include "magick/blob.h"
45 #include "magick/blob-private.h"
46 #include "magick/cache.h"
47 #include "magick/color.h"
48 #include "magick/color-private.h"
49 #include "magick/compress.h"
50 #include "magick/constitute.h"
51 #include "magick/draw.h"
52 #include "magick/exception.h"
53 #include "magick/exception-private.h"
54 #include "magick/geometry.h"
55 #include "magick/image.h"
56 #include "magick/image-private.h"
57 #include "magick/list.h"
58 #include "magick/magick.h"
59 #include "magick/memory_.h"
60 #include "magick/monitor.h"
61 #include "magick/monitor-private.h"
62 #include "magick/option.h"
63 #include "magick/property.h"
64 #include "magick/quantum-private.h"
65 #include "magick/resource_.h"
66 #include "magick/static.h"
67 #include "magick/string_.h"
68 #include "magick/module.h"
69 #include "magick/token.h"
70 #include "magick/utility.h"
71 #include "magick/module.h"
72 #if defined(MAGICKCORE_TIFF_DELEGATE)
73 #if defined(MAGICKCORE_HAVE_TIFFCONF_H)
74 #include "tiffconf.h"
75 #endif
76 #include "tiffio.h"
77 #define CCITTParam  "-1"
78 #else
79 #define CCITTParam  "0"
80 #endif
81 \f
82 /*
83   Define declarations.
84 */
85 #define PS3_NoCompression "0"
86 #define PS3_FaxCompression "1"
87 #define PS3_JPEGCompression "2"
88 #define PS3_LZWCompression "3"
89 #define PS3_RLECompression "4"
90 #define PS3_ZipCompression "5"
91
92 #define PS3_RGBColorspace "0"
93 #define PS3_CMYKColorspace "1"
94
95 #define PS3_DirectClass "0"
96 #define PS3_PseudoClass "1"
97 \f
98 /*
99   Forward declarations.
100 */
101 static MagickBooleanType
102   WritePS3Image(const ImageInfo *,Image *);
103 \f
104 /*
105 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
106 %                                                                             %
107 %                                                                             %
108 %                                                                             %
109 %   R e g i s t e r P S 3 I m a g e                                           %
110 %                                                                             %
111 %                                                                             %
112 %                                                                             %
113 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
114 %
115 %  RegisterPS3Image() adds properties for the PS3 image format to the list of
116 %  supported formats.  The properties include the image format tag, a method to
117 %  read and/or write the format, whether the format supports the saving of more
118 %  than one frame to the same file or blob, whether the format supports native
119 %  in-memory I/O, and a brief description of the format.
120 %
121 %  The format of the RegisterPS3Image method is:
122 %
123 %      unsigned long RegisterPS3Image(void)
124 %
125 */
126 ModuleExport unsigned long RegisterPS3Image(void)
127 {
128   MagickInfo
129     *entry;
130
131   entry=SetMagickInfo("EPS3");
132   entry->encoder=(EncodeImageHandler *) WritePS3Image;
133   entry->description=ConstantString("Level III Encapsulated PostScript");
134   entry->module=ConstantString("PS3");
135   (void) RegisterMagickInfo(entry);
136   entry=SetMagickInfo("PS3");
137   entry->encoder=(EncodeImageHandler *) WritePS3Image;
138   entry->description=ConstantString("Level III PostScript");
139   entry->module=ConstantString("PS3");
140   (void) RegisterMagickInfo(entry);
141   return(MagickImageCoderSignature);
142 }
143 \f
144 /*
145 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
146 %                                                                             %
147 %                                                                             %
148 %                                                                             %
149 %   U n r e g i s t e r P S 3 I m a g e                                       %
150 %                                                                             %
151 %                                                                             %
152 %                                                                             %
153 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
154 %
155 %  UnregisterPS3Image() removes format registrations made by the PS3 module
156 %  from the list of supported formats.
157 %
158 %  The format of the UnregisterPS3Image method is:
159 %
160 %      UnregisterPS3Image(void)
161 %
162 */
163 ModuleExport void UnregisterPS3Image(void)
164 {
165   (void) UnregisterMagickInfo("EPS3");
166   (void) UnregisterMagickInfo("PS3");
167 }
168 \f
169 /*
170 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
171 %                                                                             %
172 %                                                                             %
173 %                                                                             %
174 %   W r i t e P S 3 I m a g e                                                 %
175 %                                                                             %
176 %                                                                             %
177 %                                                                             %
178 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
179 %
180 %  WritePS3Image() translates an image to encapsulated Postscript Level III
181 %  for printing.  If the supplied geometry is null, the image is centered on
182 %  the Postscript page.  Otherwise, the image is positioned as specified by the
183 %  geometry.
184 %
185 %  The format of the WritePS3Image method is:
186 %
187 %      MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image)
188 %
189 %  A description of each parameter follows:
190 %
191 %    o image_info: Specifies a pointer to a ImageInfo structure.
192 %
193 %    o image: the image.
194 %
195 */
196
197 #if defined(MAGICKCORE_TIFF_DELEGATE)
198 static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info,
199   Image *image,Image *inject_image)
200 {
201   char
202     filename[MaxTextExtent];
203
204   FILE
205     *file;
206
207   Image
208     *huffman_image;
209
210   ImageInfo
211     *write_info;
212
213   int
214     unique_file;
215
216   MagickBooleanType
217     status;
218
219   register long
220     i;
221
222   ssize_t
223     count;
224
225   TIFF
226     *tiff;
227
228   uint16
229     fillorder;
230
231   uint32
232     *byte_count,
233     strip_size;
234
235   unsigned char
236     *buffer;
237
238   /*
239     Write image as CCITTFax4 TIFF image to a temporary file.
240   */
241   assert(image_info != (const ImageInfo *) NULL);
242   assert(image_info->signature == MagickSignature);
243   assert(image != (Image *) NULL);
244   assert(image->signature == MagickSignature);
245   if (image->debug != MagickFalse)
246     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
247   assert(inject_image != (Image *) NULL);
248   assert(inject_image->signature == MagickSignature);
249   huffman_image=CloneImage(inject_image,0,0,MagickTrue,&image->exception);
250   if (huffman_image == (Image *) NULL)
251     return(MagickFalse);
252   file=(FILE *) NULL;
253   unique_file=AcquireUniqueFileResource(filename);
254   if (unique_file != -1)
255     file=fdopen(unique_file,"wb"); 
256   if ((unique_file == -1) || (file == (FILE *) NULL))
257     {
258       ThrowFileException(&image->exception,FileOpenError,
259         "UnableToCreateTemporaryFile",filename);
260       return(MagickFalse);
261     }
262   (void) FormatMagickString(huffman_image->filename,MaxTextExtent,"tiff:%s",
263     filename);
264   write_info=CloneImageInfo(image_info);
265   SetImageInfoFile(write_info,file);
266   write_info->compression=Group4Compression;
267   (void) SetImageOption(write_info,"quantum:polarity","min-is-white");
268   status=WriteImage(write_info,huffman_image);
269   (void) fflush(file);
270   write_info=DestroyImageInfo(write_info);
271   if (status == MagickFalse)
272     return(MagickFalse);
273   tiff=TIFFOpen(filename,"rb");
274   if (tiff == (TIFF *) NULL)
275     {
276       huffman_image=DestroyImage(huffman_image);
277       (void) fclose(file);
278       (void) RelinquishUniqueFileResource(filename);
279       ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile",
280         image_info->filename);
281       return(MagickFalse);
282     }
283   /*
284     Allocate raw strip buffer.
285   */
286   byte_count=0;
287   (void) TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count);
288   strip_size=byte_count[0];
289   for (i=1; i < (long) TIFFNumberOfStrips(tiff); i++)
290     if (byte_count[i] > strip_size)
291       strip_size=byte_count[i];
292   buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
293     sizeof(*buffer));
294   if (buffer == (unsigned char *) NULL)
295     {
296       TIFFClose(tiff);
297       huffman_image=DestroyImage(huffman_image);
298       (void) fclose(file);
299       (void) RelinquishUniqueFileResource(filename);
300       ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
301         image_info->filename);
302     }
303   /*
304     Compress runlength encoded to 2D Huffman pixels.
305   */
306   fillorder=FILLORDER_LSB2MSB;
307   (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&fillorder);
308   for (i=0; i < (long) TIFFNumberOfStrips(tiff); i++)
309   {
310     count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,(long)
311       byte_count[i]);
312     if (fillorder == FILLORDER_LSB2MSB)
313       TIFFReverseBits(buffer,(unsigned long) count);
314     (void) WriteBlob(image,(size_t) count,buffer);
315   }
316   buffer=(unsigned char *) RelinquishMagickMemory(buffer);
317   TIFFClose(tiff);
318   huffman_image=DestroyImage(huffman_image);
319   (void) fclose(file);
320   (void) RelinquishUniqueFileResource(filename);
321   return(MagickTrue);
322 }
323 #else
324 static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info,
325   Image *image,Image *inject_image)
326 {
327   assert(image_info != (const ImageInfo *) NULL);
328   assert(image_info->signature == MagickSignature);
329   assert(image != (Image *) NULL);
330   assert(image->signature == MagickSignature);
331   if (image->debug != MagickFalse)
332     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
333   assert(inject_image != (Image *) NULL);
334   assert(inject_image->signature == MagickSignature);
335   (void) ThrowMagickException(&image->exception,GetMagickModule(),
336     MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (TIFF)",
337     image->filename);
338   return(MagickFalse);
339 }
340 #endif
341
342 static MagickBooleanType SerializeImage(const ImageInfo *image_info,
343   Image *image,unsigned char **pixels,size_t *length)
344 {
345   long
346     y;
347
348   MagickBooleanType
349     status;
350
351   register const IndexPacket
352     *indexes;
353
354   register const PixelPacket
355     *p;
356
357   register long
358     x;
359
360   register unsigned char
361     *q;
362
363   assert(image != (Image *) NULL);
364   assert(image->signature == MagickSignature);
365   if (image->debug != MagickFalse)
366     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
367   status=MagickTrue;
368   *length=(image->colorspace == CMYKColorspace ? 4 : 3)*
369     (size_t) image->columns*image->rows;
370   *pixels=(unsigned char *) AcquireQuantumMemory(*length,sizeof(**pixels));
371   if (*pixels == (unsigned char *) NULL)
372     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
373   q=(*pixels);
374   for (y=0; y < (long) image->rows; y++)
375   {
376     p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
377     if (p == (const PixelPacket *) NULL)
378       break;
379     indexes=GetVirtualIndexQueue(image);
380     if (image->colorspace != CMYKColorspace)
381       for (x=0; x < (long) image->columns; x++)
382       {
383         *q++=ScaleQuantumToChar(p->red);
384         *q++=ScaleQuantumToChar(p->green);
385         *q++=ScaleQuantumToChar(p->blue);
386         p++;
387       }
388     else
389       for (x=0; x < (long) image->columns; x++)
390       {
391         *q++=ScaleQuantumToChar(p->red);
392         *q++=ScaleQuantumToChar(p->green);
393         *q++=ScaleQuantumToChar(p->blue);
394         *q++=ScaleQuantumToChar(indexes[x]);
395         p++;
396       }
397     if (image->previous == (Image *) NULL)
398       {
399         status=SetImageProgress(image,SaveImageTag,y,image->rows);
400         if (status == MagickFalse)
401           break;
402       }
403   }
404   if (status == MagickFalse)
405     *pixels=(unsigned char *) RelinquishMagickMemory(*pixels);
406   return(status);
407 }
408
409 static MagickBooleanType SerializeImageChannel(const ImageInfo *image_info,
410   Image *image,unsigned char **pixels,size_t *length)
411 {
412   long
413     y;
414
415   MagickBooleanType
416     status;
417
418   register const PixelPacket
419     *p;
420
421   register long
422     x;
423
424   register unsigned char
425     *q;
426
427   unsigned char
428     code,
429     bit;
430
431   unsigned long
432     pack,
433     padded_columns;
434
435   assert(image != (Image *) NULL);
436   assert(image->signature == MagickSignature);
437   if (image->debug != MagickFalse)
438     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
439   status=MagickTrue;
440   pack=IsMonochromeImage(image,&image->exception) == MagickFalse ? 1UL : 8UL;
441   padded_columns=((image->columns+pack-1)/pack)*pack;
442   *length=(size_t) padded_columns*image->rows/pack;
443   *pixels=(unsigned char *) AcquireQuantumMemory(*length,sizeof(**pixels));
444   if (*pixels == (unsigned char *) NULL)
445     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
446   q=(*pixels);
447   for (y=0; y < (long) image->rows; y++)
448   {
449     p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
450     if (p == (const PixelPacket *) NULL)
451       break;
452     if (pack == 1)
453       for (x=0; x < (long) image->columns; x++)
454       {
455         *q++=ScaleQuantumToChar(PixelIntensityToQuantum(p));
456         p++;
457       }
458     else
459       {
460         code='\0';
461         for (x=0; x < (long) padded_columns; x++)
462         {
463           bit=(unsigned char) 0x00;
464           if (x < (long) image->columns)
465             bit=(unsigned char) (PixelIntensityToQuantum(p) ==
466               (Quantum) TransparentOpacity ? 0x01 : 0x00);
467           code=(code << 1)+bit;
468           if (((x+1) % pack) == 0)
469             {
470               *q++=code;
471               code='\0';
472             }
473           p++;
474         }
475       }
476     status=SetImageProgress(image,SaveImageTag,y,image->rows);
477     if (status == MagickFalse)
478       break;
479   }
480   if (status == MagickFalse)
481     *pixels=(unsigned char *) RelinquishMagickMemory(*pixels);
482   return(status);
483 }
484
485 static MagickBooleanType SerializeImageIndexes(const ImageInfo *image_info,
486   Image *image,unsigned char **pixels,size_t *length)
487 {
488   long
489     y;
490
491   MagickBooleanType
492     status;
493
494   register const IndexPacket
495     *indexes;
496
497   register const PixelPacket
498     *p;
499
500   register long
501     x;
502
503   register unsigned char
504     *q;
505
506   assert(image != (Image *) NULL);
507   assert(image->signature == MagickSignature);
508   if (image->debug != MagickFalse)
509     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
510   status=MagickTrue;
511   *length=(size_t) image->columns*image->rows;
512   *pixels=(unsigned char *) AcquireQuantumMemory(*length,sizeof(**pixels));
513   if (*pixels == (unsigned char *) NULL)
514     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
515   q=(*pixels);
516   for (y=0; y < (long) image->rows; y++)
517   {
518     p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
519     if (p == (const PixelPacket *) NULL)
520       break;
521     indexes=GetVirtualIndexQueue(image);
522     for (x=0; x < (long) image->columns; x++)
523       *q++=(unsigned char) indexes[x];
524     if (image->previous == (Image *) NULL)
525       {
526         status=SetImageProgress(image,SaveImageTag,y,image->rows);
527         if (status == MagickFalse)
528           break;
529       }
530   }
531   if (status == MagickFalse)
532     *pixels=(unsigned char *) RelinquishMagickMemory(*pixels);
533   return(status);
534 }
535
536 static MagickBooleanType WritePS3MaskImage(const ImageInfo *image_info,
537   Image *image,const CompressionType compression)
538 {
539   char
540     buffer[MaxTextExtent];
541
542   Image
543     *mask_image;
544
545   MagickBooleanType
546     status;
547
548   MagickOffsetType
549     offset,
550     start,
551     stop;
552
553   register long
554     i;
555
556   size_t
557     length;
558
559   unsigned char
560     *pixels;
561
562   assert(image_info != (ImageInfo *) NULL);
563   assert(image_info->signature == MagickSignature);
564   assert(image != (Image *) NULL);
565   assert(image->signature == MagickSignature);
566   if (image->debug != MagickFalse)
567     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
568   assert(image->matte != MagickFalse);
569   status=MagickTrue;
570   /*
571     Note BeginData DSC comment for update later.
572   */
573   start=TellBlob(image);
574   (void) FormatMagickString(buffer,MaxTextExtent,
575     "%%%%BeginData:%13ld %s Bytes\n",0L,
576     compression == NoCompression ? "ASCII" : "BINARY");
577   (void) WriteBlobString(image,buffer);
578   stop=TellBlob(image);
579   /*
580     Only lossless compressions for the mask.
581   */
582   switch (compression)
583   {
584     case NoCompression:
585     default:
586     {
587       (void) FormatMagickString(buffer,MaxTextExtent,
588         "currentfile %lu %lu "PS3_NoCompression" ByteStreamDecodeFilter\n",
589         image->columns,image->rows);
590       break;
591     }
592     case FaxCompression:
593     case Group4Compression:
594     {
595       (void) FormatMagickString(buffer,MaxTextExtent,
596         "currentfile %lu %lu "PS3_FaxCompression" ByteStreamDecodeFilter\n",
597         image->columns,image->rows);
598       break;
599     }
600     case LZWCompression:
601     {
602       (void) FormatMagickString(buffer,MaxTextExtent,
603         "currentfile %lu %lu "PS3_LZWCompression" ByteStreamDecodeFilter\n",
604         image->columns,image->rows);
605       break;
606     }
607     case RLECompression:
608     {
609       (void) FormatMagickString(buffer,MaxTextExtent,
610         "currentfile %lu %lu "PS3_RLECompression" ByteStreamDecodeFilter\n",
611         image->columns,image->rows);
612       break;
613     }
614     case ZipCompression:
615     {
616       (void) FormatMagickString(buffer,MaxTextExtent,
617         "currentfile %lu %lu "PS3_ZipCompression" ByteStreamDecodeFilter\n",
618         image->columns,image->rows);
619       break;
620     }
621   }
622   (void) WriteBlobString(image,buffer);
623   (void) WriteBlobString(image,"/ReusableStreamDecode filter\n");
624   mask_image=CloneImage(image,0,0,MagickTrue,&image->exception);
625   if (mask_image == (Image *) NULL)
626     ThrowWriterException(CoderError,image->exception.reason);
627   status=SeparateImageChannel(mask_image,OpacityChannel);
628   if (status == MagickFalse)
629     {
630       mask_image=DestroyImage(mask_image);
631       return(MagickFalse);
632     }
633   (void) SetImageType(mask_image,BilevelType);
634   (void) SetImageType(mask_image,PaletteType);
635   mask_image->matte=MagickFalse;
636   pixels=(unsigned char *) NULL;
637   length=0;
638   switch (compression)
639   {
640     case NoCompression:
641     default:
642     {
643       status=SerializeImageChannel(image_info,mask_image,&pixels,&length);
644       if (status == MagickFalse)
645         break;
646       Ascii85Initialize(image);
647       for (i=0; i < (long) length; i++)
648         Ascii85Encode(image,pixels[i]);
649       Ascii85Flush(image);
650       pixels=(unsigned char *) RelinquishMagickMemory(pixels);
651       break;
652     }
653     case FaxCompression:
654     case Group4Compression:
655     {
656       if ((compression == FaxCompression) ||
657           (LocaleCompare(CCITTParam,"0") == 0))
658         status=HuffmanEncodeImage(image_info,image,mask_image);
659       else
660         status=Huffman2DEncodeImage(image_info,image,mask_image);
661       break;
662     }
663     case LZWCompression:
664     {
665       status=SerializeImageChannel(image_info,mask_image,&pixels,&length);
666       if (status == MagickFalse)
667         break;
668       status=LZWEncodeImage(image,length,pixels);
669       pixels=(unsigned char *) RelinquishMagickMemory(pixels);
670       break;
671     }
672     case RLECompression:
673     {
674       status=SerializeImageChannel(image_info,mask_image,&pixels,&length);
675       if (status == MagickFalse)
676         break;
677       status=PackbitsEncodeImage(image,length,pixels);
678       pixels=(unsigned char *) RelinquishMagickMemory(pixels);
679       break;
680     }
681     case ZipCompression:
682     {
683       status=SerializeImageChannel(image_info,mask_image,&pixels,&length);
684       if (status == MagickFalse)
685         break;
686       status=ZLIBEncodeImage(image,length,pixels);
687       pixels=(unsigned char *) RelinquishMagickMemory(pixels);
688       break;
689     }
690   }
691   mask_image=DestroyImage(mask_image);
692   (void) WriteBlobByte(image,'\n');
693   length=(size_t) (TellBlob(image)-stop);
694   stop=TellBlob(image);
695   offset=SeekBlob(image,start,SEEK_SET);
696   if (offset < 0)
697     ThrowWriterException(CorruptImageError,"ImproperImageHeader");
698   (void) FormatMagickString(buffer,MaxTextExtent,
699     "%%%%BeginData:%13ld %s Bytes\n",(long) length,
700     compression == NoCompression ? "ASCII" : "BINARY");
701   (void) WriteBlobString(image,buffer);
702   offset=SeekBlob(image,stop,SEEK_SET);
703   if (offset < 0)
704     ThrowWriterException(CorruptImageError,"ImproperImageHeader");
705   (void) WriteBlobString(image,"%%EndData\n");
706   (void) WriteBlobString(image, "/mask_stream exch def\n");
707   return(status);
708 }
709
710 static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image)
711 {
712   static const char
713     *PostscriptProlog[]=
714     {
715       "/ByteStreamDecodeFilter",
716       "{",
717       "  /z exch def",
718       "  /r exch def",
719       "  /c exch def",
720       "  z "PS3_NoCompression" eq { /ASCII85Decode filter } if",
721       "  z "PS3_FaxCompression" eq",
722       "  {",
723       "    <<",
724       "      /K "CCITTParam,
725       "      /Columns c",
726       "      /Rows r",
727       "    >>",
728       "    /CCITTFaxDecode filter",
729       "  } if",
730       "  z "PS3_JPEGCompression" eq { /DCTDecode filter } if",
731       "  z "PS3_LZWCompression" eq { /LZWDecode filter } if",
732       "  z "PS3_RLECompression" eq { /RunLengthDecode filter } if",
733       "  z "PS3_ZipCompression" eq { /FlateDecode filter } if",
734       "} bind def",
735       "",
736       "/DirectClassImageDict",
737       "{",
738       "  colorspace "PS3_RGBColorspace" eq",
739       "  {",
740       "    /DeviceRGB setcolorspace",
741       "    <<",
742       "      /ImageType 1",
743       "      /Width columns",
744       "      /Height rows",
745       "      /BitsPerComponent 8",
746       "      /DataSource pixel_stream",
747       "      /MultipleDataSources false",
748       "      /ImageMatrix [columns 0 0 rows neg 0 rows]",
749       "      /Decode [0 1 0 1 0 1]",
750       "    >>",
751       "  }",
752       "  {",
753       "    /DeviceCMYK setcolorspace",
754       "    <<",
755       "      /ImageType 1",
756       "      /Width columns",
757       "      /Height rows",
758       "      /BitsPerComponent 8",
759       "      /DataSource pixel_stream",
760       "      /MultipleDataSources false",
761       "      /ImageMatrix [columns 0 0 rows neg 0 rows]",
762       "      /Decode",
763       "        compression "PS3_JPEGCompression" eq",
764       "        { [1 0 1 0 1 0 1 0] }",
765       "        { [0 1 0 1 0 1 0 1] }",
766       "        ifelse",
767       "    >>",
768       "  }",
769       "  ifelse",
770       "} bind def",
771       "",
772       "/PseudoClassImageDict",
773       "{",
774       "  % Colors in colormap image.",
775       "  currentfile buffer readline pop",
776       "  token pop /colors exch def pop",
777       "  colors 0 eq",
778       "  {",
779       "    % Depth of grayscale image.",
780       "    currentfile buffer readline pop",
781       "    token pop /bits exch def pop",
782       "    /DeviceGray setcolorspace",
783       "    <<",
784       "      /ImageType 1",
785       "      /Width columns",
786       "      /Height rows",
787       "      /BitsPerComponent bits",
788       "      /Decode [0 1]",
789       "      /ImageMatrix [columns 0 0 rows neg 0 rows]",
790       "      /DataSource pixel_stream",
791       "    >>",
792       "  }",
793       "  {",
794       "    % RGB colormap.",
795       "    /colormap colors 3 mul string def",
796       "    compression "PS3_NoCompression" eq",
797       "    { currentfile /ASCII85Decode filter colormap readstring pop pop }",
798       "    { currentfile colormap readstring pop pop }",
799       "    ifelse",
800       "    [ /Indexed /DeviceRGB colors 1 sub colormap ] setcolorspace",
801       "    <<",
802       "      /ImageType 1",
803       "      /Width columns",
804       "      /Height rows",
805       "      /BitsPerComponent 8",
806       "      /Decode [0 255]",
807       "      /ImageMatrix [columns 0 0 rows neg 0 rows]",
808       "      /DataSource pixel_stream",
809       "    >>",
810       "  }",
811       "  ifelse",
812       "} bind def",
813       "",
814       "/NonMaskedImageDict",
815       "{",
816       "  class "PS3_PseudoClass" eq",
817       "  { PseudoClassImageDict }",
818       "  { DirectClassImageDict }",
819       "  ifelse",
820       "} bind def",
821       "",
822       "/MaskedImageDict",
823       "{",
824       "  <<",
825       "    /ImageType 3",
826       "    /InterleaveType 3",
827       "    /DataDict NonMaskedImageDict",
828       "    /MaskDict",
829       "    <<",
830       "      /ImageType 1",
831       "      /Width columns",
832       "      /Height rows",
833       "      /BitsPerComponent 1",
834       "      /DataSource mask_stream",
835       "      /MultipleDataSources false",
836       "      /ImageMatrix [ columns 0 0 rows neg 0 rows]",
837       "      /Decode [ 0 1 ]",
838       "    >>",
839       "  >>",
840       "} bind def",
841       "",
842       "/ClipImage",
843       "{} def",
844       "",
845       "/DisplayImage",
846       "{",
847       "  /buffer 512 string def",
848       "  % Translation.",
849       "  currentfile buffer readline pop",
850       "  token pop /x exch def",
851       "  token pop /y exch def pop",
852       "  x y translate",
853       "  % Image size and font size.",
854       "  currentfile buffer readline pop",
855       "  token pop /x exch def",
856       "  token pop /y exch def pop",
857       "  currentfile buffer readline pop",
858       "  token pop /pointsize exch def pop",
859       (char *) NULL
860     },
861     *PostscriptEpilog[]=
862     {
863       "  x y scale",
864       "  % Clipping path.",
865       "  currentfile buffer readline pop",
866       "  token pop /clipped exch def pop",
867       "  % Showpage.",
868       "  currentfile buffer readline pop",
869       "  token pop /sp exch def pop",
870       "  % Image pixel size.",
871       "  currentfile buffer readline pop",
872       "  token pop /columns exch def",
873       "  token pop /rows exch def pop",
874       "  % Colorspace (RGB/CMYK).",
875       "  currentfile buffer readline pop",
876       "  token pop /colorspace exch def pop",
877       "  % Transparency.",
878       "  currentfile buffer readline pop",
879       "  token pop /alpha exch def pop",
880       "  % Stencil mask?",
881       "  currentfile buffer readline pop",
882       "  token pop /stencil exch def pop",
883       "  % Image class (direct/pseudo).",
884       "  currentfile buffer readline pop",
885       "  token pop /class exch def pop",
886       "  % Compression type.",
887       "  currentfile buffer readline pop",
888       "  token pop /compression exch def pop",
889       "  % Clip and render.",
890       "  /pixel_stream currentfile columns rows compression ByteStreamDecodeFilter def",
891       "  clipped { ClipImage } if",
892       "  alpha stencil not and",
893       "  { MaskedImageDict mask_stream resetfile }",
894       "  { NonMaskedImageDict }",
895       "  ifelse",
896       "  stencil { 0 setgray imagemask } { image } ifelse",
897       "  sp { showpage } if",
898       "} bind def",
899       (char *) NULL
900     };
901
902   char
903     buffer[MaxTextExtent],
904     date[MaxTextExtent],
905     **labels,
906     page_geometry[MaxTextExtent];
907
908   CompressionType
909     compression;
910
911   const char
912     *option,
913     **q,
914     *value;
915
916   double
917     pointsize;
918
919   GeometryInfo
920     geometry_info;
921
922   long
923     j;
924
925   MagickBooleanType
926     status;
927
928   MagickOffsetType
929     offset,
930     scene,
931     start,
932     stop;
933
934   MagickStatusType
935     flags;
936
937   PointInfo
938     delta,
939     resolution,
940     scale;
941
942   RectangleInfo
943     geometry,
944     media_info,
945     page_info;
946
947   register long
948     i;
949
950   SegmentInfo
951     bounds;
952
953   size_t
954     length;
955
956   time_t
957     timer;
958
959   unsigned char
960     *pixels;
961
962   unsigned long
963     page,
964     pixel,
965     text_size;
966
967   /*
968     Open output image file.
969   */
970   assert(image_info != (const ImageInfo *) NULL);
971   assert(image_info->signature == MagickSignature);
972   assert(image != (Image *) NULL);
973   assert(image->signature == MagickSignature);
974   if (image->debug != MagickFalse)
975     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
976   status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
977   if (status == MagickFalse)
978     return(MagickFalse);
979   compression=image->compression;
980   if (image_info->compression != UndefinedCompression)
981     compression=image_info->compression;
982   switch (compression)
983   {
984     case FaxCompression:
985     case Group4Compression:
986     { 
987       if ((IsMonochromeImage(image,&image->exception) == MagickFalse) ||
988           (image->matte != MagickFalse))
989         compression=RLECompression;
990       break;
991     }
992 #if !defined(MAGICKCORE_JPEG_DELEGATE)
993     case JPEGCompression:
994     {
995       compression=RLECompression;
996       (void) ThrowMagickException(&image->exception,GetMagickModule(),
997         MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)",
998         image->filename);
999       break;
1000     }
1001 #endif
1002 #if !defined(MAGICKCORE_ZLIB_DELEGATE)
1003     case ZipCompression:
1004     {
1005       compression=RLECompression;
1006       (void) ThrowMagickException(&image->exception,GetMagickModule(),
1007         MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)",
1008         image->filename);
1009       break;
1010     }
1011 #endif
1012     default:
1013       break;
1014   }
1015   (void) ResetMagickMemory(&bounds,0,sizeof(bounds));
1016   page=0;
1017   scene=0;
1018   do
1019   {
1020     /*
1021       Scale relative to dots-per-inch.
1022     */
1023     delta.x=DefaultResolution;
1024     delta.y=DefaultResolution;
1025     resolution.x=image->x_resolution;
1026     resolution.y=image->y_resolution;
1027     if ((resolution.x == 0.0) || (resolution.y == 0.0))
1028       {
1029         flags=ParseGeometry(PSDensityGeometry,&geometry_info);
1030         resolution.x=geometry_info.rho;
1031         resolution.y=geometry_info.sigma;
1032         if ((flags & SigmaValue) == 0)
1033           resolution.y=resolution.x;
1034       }
1035     if (image_info->density != (char *) NULL)
1036       {
1037         flags=ParseGeometry(image_info->density,&geometry_info);
1038         resolution.x=geometry_info.rho;
1039         resolution.y=geometry_info.sigma;
1040         if ((flags & SigmaValue) == 0)
1041           resolution.y=resolution.x;
1042       }
1043     if (image->units == PixelsPerCentimeterResolution)
1044       {
1045         resolution.x*=2.54;
1046         resolution.y*=2.54;
1047       }
1048     SetGeometry(image,&geometry);
1049     (void) FormatMagickString(page_geometry,MaxTextExtent,"%lux%lu",
1050       image->columns,image->rows);
1051     if (image_info->page != (char *) NULL)
1052       (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent);
1053     else
1054       if ((image->page.width != 0) && (image->page.height != 0))
1055         (void) FormatMagickString(page_geometry,MaxTextExtent,"%lux%lu%+ld%+ld",
1056           image->page.width,image->page.height,image->page.x,image->page.y);
1057       else
1058         if ((image->gravity != UndefinedGravity) &&
1059             (LocaleCompare(image_info->magick,"PS") == 0))
1060           (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent);
1061     (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent);
1062     (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,
1063       &geometry.width,&geometry.height);
1064     scale.x=(double) (geometry.width*delta.x)/resolution.x;
1065     geometry.width=(unsigned long) (scale.x+0.5);
1066     scale.y=(double) (geometry.height*delta.y)/resolution.y;
1067     geometry.height=(unsigned long) (scale.y+0.5);
1068     (void) ParseAbsoluteGeometry(page_geometry,&media_info);
1069     (void) ParseGravityGeometry(image,page_geometry,&page_info,
1070       &image->exception);
1071     if (image->gravity != UndefinedGravity)
1072       {
1073         geometry.x=(-page_info.x);
1074         geometry.y=(long) (media_info.height+page_info.y-image->rows);
1075       }
1076     pointsize=12.0;
1077     if (image_info->pointsize != 0.0)
1078       pointsize=image_info->pointsize;
1079     text_size=0;
1080     value=GetImageProperty(image,"label");
1081     if (value != (const char *) NULL)
1082       text_size=(unsigned long) (MultilineCensus(value)*pointsize+12);
1083     page++;
1084     if (page == 1)
1085       {
1086         /*
1087           Postscript header on the first page.
1088         */
1089         if (LocaleCompare(image_info->magick,"PS3") == 0)
1090           (void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MaxTextExtent);
1091         else
1092           (void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n",
1093             MaxTextExtent);
1094         (void) WriteBlobString(image,buffer);
1095         (void) FormatMagickString(buffer,MaxTextExtent,
1096           "%%%%Creator: ImageMagick %s\n",MagickLibVersionText);
1097         (void) WriteBlobString(image,buffer);
1098         (void) FormatMagickString(buffer,MaxTextExtent,"%%%%Title: %s\n",
1099           image->filename);
1100         (void) WriteBlobString(image,buffer);
1101         timer=time((time_t *) NULL);
1102         (void) FormatMagickTime(timer,MaxTextExtent,date);
1103         (void) FormatMagickString(buffer,MaxTextExtent,
1104           "%%%%CreationDate: %s\n",date);
1105         (void) WriteBlobString(image,buffer);
1106         bounds.x1=(double) geometry.x;
1107         bounds.y1=(double) geometry.y;
1108         bounds.x2=(double) geometry.x+scale.x;
1109         bounds.y2=(double) geometry.y+scale.y+text_size;
1110         if ((image_info->adjoin != MagickFalse) &&
1111             (GetNextImageInList(image) != (Image *) NULL))
1112           {
1113             (void) WriteBlobString(image,"%%BoundingBox: (atend)\n");
1114             (void) WriteBlobString(image,"%%HiResBoundingBox: (atend)\n");
1115           }
1116         else
1117           {
1118             (void) FormatMagickString(buffer,MaxTextExtent,
1119               "%%%%BoundingBox: %g %g %g %g\n",floor(bounds.x1+0.5),
1120               floor(bounds.y1+0.5),ceil(bounds.x2-0.5),ceil(bounds.y2-0.5));
1121             (void) WriteBlobString(image,buffer);
1122             (void) FormatMagickString(buffer,MaxTextExtent,
1123               "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1,
1124               bounds.x2,bounds.y2);
1125             (void) WriteBlobString(image,buffer);
1126             if (image->colorspace == CMYKColorspace)
1127               (void) WriteBlobString(image,
1128                 "%%DocumentProcessColors: Cyan Magenta Yellow Black\n");
1129             else
1130               if (IsGrayImage(image,&image->exception) != MagickFalse)
1131                 (void) WriteBlobString(image,
1132                   "%%DocumentProcessColors: Black\n");
1133           }
1134         /*
1135           Font resources
1136         */
1137         value=GetImageProperty(image,"label");
1138         if (value != (const char *) NULL)
1139           (void) WriteBlobString(image,
1140             "%%DocumentNeededResources: font Helvetica\n");
1141         (void) WriteBlobString(image,"%%LanguageLevel: 3\n");
1142         /*
1143           Pages, orientation and order.
1144         */
1145         if (LocaleCompare(image_info->magick,"PS3") != 0)
1146           (void) WriteBlobString(image,"%%Pages: 1\n");
1147         else
1148           {
1149             (void) WriteBlobString(image,"%%Orientation: Portrait\n");
1150             (void) WriteBlobString(image,"%%PageOrder: Ascend\n");
1151             if (image_info->adjoin == MagickFalse)
1152               (void) CopyMagickString(buffer,"%%Pages: 1\n",MaxTextExtent);
1153             else
1154               (void) FormatMagickString(buffer,MaxTextExtent,"%%%%Pages: %lu\n",
1155                 (unsigned long) GetImageListLength(image));
1156             (void) WriteBlobString(image,buffer);
1157           }
1158         (void) WriteBlobString(image,"%%EndComments\n");
1159         /*
1160           The static postscript procedures prolog.
1161         */
1162         (void)WriteBlobString(image,"%%BeginProlog\n");
1163         for (q=PostscriptProlog; *q; q++)
1164         {
1165           (void) WriteBlobString(image,*q);
1166           (void) WriteBlobByte(image,'\n');
1167         }
1168         /*
1169           One label line for each line in label string.
1170         */
1171         value=GetImageProperty(image,"label");
1172         if (value != (const char *) NULL)
1173           {
1174               (void) WriteBlobString(image,"\n  %% Labels.\n  /Helvetica "
1175               " findfont pointsize scalefont setfont\n");
1176             for (i=(long) MultilineCensus(value)-1; i >= 0; i--)
1177             {
1178               (void) WriteBlobString(image,
1179                 "  currentfile buffer readline pop token pop\n");
1180               (void) FormatMagickString(buffer,MaxTextExtent,
1181                 "  0 y %g add moveto show pop\n",i*pointsize+12);
1182               (void) WriteBlobString(image,buffer);
1183             }
1184           }
1185         /*
1186           The static postscript procedures epilog.
1187         */
1188         for (q=PostscriptEpilog; *q; q++)
1189         {
1190           (void) WriteBlobString(image,*q);
1191           (void) WriteBlobByte(image,'\n');
1192         }
1193         (void)WriteBlobString(image,"%%EndProlog\n");
1194       }
1195     (void) FormatMagickString(buffer,MaxTextExtent,"%%%%Page: 1 %lu\n",page);
1196     (void) WriteBlobString(image,buffer);
1197     /*
1198       Page bounding box.
1199     */
1200     (void) FormatMagickString(buffer,MaxTextExtent,
1201       "%%%%PageBoundingBox: %ld %ld %ld %ld\n",geometry.x,geometry.y,geometry.x+
1202       (long) geometry.width,geometry.y+(long) (geometry.height+text_size));
1203     (void) WriteBlobString(image,buffer);
1204     /*
1205       Page process colors if not RGB.
1206     */
1207     if (image->colorspace == CMYKColorspace)
1208       (void) WriteBlobString(image,
1209         "%%PageProcessColors: Cyan Magenta Yellow Black\n");
1210     else
1211       if (IsGrayImage(image,&image->exception) != MagickFalse)
1212         (void) WriteBlobString(image,"%%PageProcessColors: Black\n");
1213     /*
1214       Adjust document bounding box to bound page bounding box.
1215     */
1216     if ((double) geometry.x < bounds.x1)
1217       bounds.x1=(double) geometry.x;
1218     if ((double) geometry.y < bounds.y1)
1219       bounds.y1=(double) geometry.y;
1220     if ((double) (geometry.x+scale.x) > bounds.x2)
1221       bounds.x2=(double) geometry.x+scale.x;
1222     if ((double) (geometry.y+scale.y+text_size) > bounds.y2)
1223       bounds.y2=(double) geometry.y+scale.y+text_size;
1224     /*
1225       Page font resource if there's a label.
1226     */
1227     value=GetImageProperty(image,"label");
1228     if (value != (const char *) NULL)
1229       (void) WriteBlobString(image,"%%PageResources: font Helvetica\n");
1230     /*
1231       PS clipping path from Photoshop clipping path.
1232     */
1233     if ((image->clip_mask == (Image *) NULL) ||
1234         (LocaleNCompare("8BIM:",image->clip_mask->magick_filename,5) != 0))
1235       (void) WriteBlobString(image,"/ClipImage {} def\n");
1236     else
1237       {
1238         const char
1239           *value;
1240
1241         value=GetImageProperty(image,image->clip_mask->magick_filename);
1242         if (value == (const char *) NULL)
1243           return(MagickFalse);
1244         (void) WriteBlobString(image,value);
1245         (void) WriteBlobByte(image,'\n');
1246       }
1247     /*
1248       Push a dictionary for our own def's if this an EPS.
1249     */
1250     if (LocaleCompare(image_info->magick,"PS3") != 0)
1251       (void) WriteBlobString(image,"userdict begin\n");
1252     /*
1253       Image mask.
1254     */
1255     if ((image->matte != MagickFalse) &&
1256         (WritePS3MaskImage(image_info,image,compression) == MagickFalse))
1257       {
1258         (void) CloseBlob(image);
1259         return(MagickFalse);
1260       }
1261     /*
1262       Remember position of BeginData comment so we can update it.
1263     */
1264     start=TellBlob(image);
1265     (void) FormatMagickString(buffer,MaxTextExtent,
1266       "%%%%BeginData:%13ld %s Bytes\n",0L,
1267       compression == NoCompression ? "ASCII" : "BINARY");
1268     (void) WriteBlobString(image,buffer);
1269     stop=TellBlob(image);
1270     (void) WriteBlobString(image,"DisplayImage\n");
1271     /*
1272       Translate, scale, and font point size.
1273     */
1274     (void) FormatMagickString(buffer,MaxTextExtent,"%ld %ld\n%g %g\n%f\n",
1275       geometry.x,geometry.y,scale.x,scale.y,pointsize);
1276     (void) WriteBlobString(image,buffer);
1277     /*
1278       Output labels.
1279     */
1280     labels=(char **) NULL;
1281     value=GetImageProperty(image,"label");
1282     if (value != (const char *) NULL)
1283       labels=StringToList(value);
1284     if (labels != (char **) NULL)
1285       {
1286         for (i=0; labels[i] != (char *) NULL; i++)
1287         {
1288           if (compression != NoCompression)
1289             {
1290               for (j=0; labels[i][j] != '\0'; j++)
1291                 (void) WriteBlobByte(image,(unsigned char) labels[i][j]);
1292               (void) WriteBlobByte(image,'\n');
1293             }
1294           else
1295             {
1296               (void) WriteBlobString(image,"<~");
1297               Ascii85Initialize(image);
1298               for (j=0; labels[i][j] != '\0'; j++)
1299                 Ascii85Encode(image,(unsigned char) labels[i][j]);
1300               Ascii85Flush(image);
1301             }
1302           labels[i]=DestroyString(labels[i]);
1303         }
1304         labels=(char **) RelinquishMagickMemory(labels);
1305       }
1306     /*
1307       Photoshop clipping path active?
1308     */
1309     if ((image->clip_mask != (Image *) NULL) &&
1310         (LocaleNCompare("8BIM:",image->clip_mask->magick_filename,5) == 0))
1311         (void) WriteBlobString(image,"true\n");
1312       else
1313         (void) WriteBlobString(image,"false\n");
1314     /*
1315       Showpage for non-EPS.
1316     */
1317     (void) WriteBlobString(image, LocaleCompare(image_info->magick,"PS3") == 0 ?
1318       "true\n" : "false\n");
1319     /*
1320       Image columns, rows, and color space.
1321     */
1322     (void) FormatMagickString(buffer,MaxTextExtent,"%lu %lu\n%s\n",
1323       image->columns,image->rows,image->colorspace == CMYKColorspace ?
1324       PS3_CMYKColorspace : PS3_RGBColorspace);
1325     (void) WriteBlobString(image,buffer);
1326     /*
1327       Masked image?
1328     */
1329     (void) WriteBlobString(image,image->matte != MagickFalse ?
1330       "true\n" : "false\n");
1331     /*
1332       Render with imagemask operator?
1333     */
1334     option=GetImageOption(image_info,"ps3:imagemask");
1335     (void) WriteBlobString(image,((option != (const char *) NULL) &&
1336       (IsMonochromeImage(image,&image->exception) != MagickFalse)) ?
1337       "true\n" : "false\n");
1338     /*
1339       Output pixel data.
1340     */
1341     pixels=(unsigned char *) NULL;
1342     length=0;
1343     if ((image_info->type != TrueColorType) &&
1344         (image_info->type != TrueColorMatteType) &&
1345         (image_info->type != ColorSeparationType) &&
1346         (image_info->type != ColorSeparationMatteType) &&
1347         (image->colorspace != CMYKColorspace) &&
1348         ((IsGrayImage(image,&image->exception) != MagickFalse) ||
1349          (IsMonochromeImage(image,&image->exception) != MagickFalse)))
1350       {
1351         /*
1352           Gray images.
1353         */
1354         (void) WriteBlobString(image,PS3_PseudoClass"\n");
1355         switch (compression)
1356         {
1357           case NoCompression:
1358           default:
1359           {
1360             (void) WriteBlobString(image,PS3_NoCompression"\n");
1361             break;
1362           }
1363           case FaxCompression:
1364           case Group4Compression:
1365           {
1366             (void) WriteBlobString(image,PS3_FaxCompression"\n");
1367             break;
1368           }
1369           case JPEGCompression:
1370           {
1371             (void) WriteBlobString(image,PS3_JPEGCompression"\n");
1372             break;
1373           }
1374           case LZWCompression:
1375           {
1376             (void) WriteBlobString(image,PS3_LZWCompression"\n");
1377             break;
1378           }
1379           case RLECompression:
1380           {
1381             (void) WriteBlobString(image,PS3_RLECompression"\n");
1382             break;
1383           }
1384           case ZipCompression:
1385           {
1386             (void) WriteBlobString(image,PS3_ZipCompression"\n");
1387             break;
1388           }
1389         }
1390         /*
1391           Number of colors -- 0 for single component non-color mapped data.
1392         */
1393         (void) WriteBlobString(image,"0\n");
1394         /*
1395           1 bit or 8 bit components?
1396         */
1397         (void) FormatMagickString(buffer,MaxTextExtent,"%d\n",
1398           IsMonochromeImage(image,&image->exception) != MagickFalse ? 1 : 8);
1399         (void) WriteBlobString(image,buffer);
1400         /*
1401           Image data.
1402         */
1403         if (compression == JPEGCompression)
1404           status=InjectImageBlob(image_info,image,image,"jpeg",
1405             &image->exception);
1406         else
1407           if ((compression == FaxCompression) ||
1408               (compression == Group4Compression))
1409             {
1410               if (LocaleCompare(CCITTParam,"0") == 0)
1411                 status=HuffmanEncodeImage(image_info,image,image);
1412               else
1413                 status=Huffman2DEncodeImage(image_info,image,image);
1414             }
1415           else
1416             {
1417               status=SerializeImageChannel(image_info,image,&pixels,&length);
1418               if (status == MagickFalse)
1419                 {
1420                   (void) CloseBlob(image);
1421                   return(MagickFalse);
1422                 }
1423               switch (compression)
1424               {
1425                 case NoCompression:
1426                 default:
1427                 {
1428                   Ascii85Initialize(image);
1429                   for (i=0; i < (long) length; i++)
1430                     Ascii85Encode(image,pixels[i]);
1431                   Ascii85Flush(image);
1432                   status=MagickTrue;
1433                   break;
1434                 }
1435                 case LZWCompression:
1436                 {
1437                   status=LZWEncodeImage(image,length,pixels);
1438                   break;
1439                 }
1440                 case RLECompression:
1441                 {
1442                   status=PackbitsEncodeImage(image,length,pixels);
1443                   break;
1444                 }
1445                 case ZipCompression:
1446                 {
1447                   status=ZLIBEncodeImage(image,length,pixels);
1448                   break;
1449                 }
1450               }
1451               pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1452             }
1453       }
1454     else
1455       if ((image->storage_class == DirectClass) || (image->colors > 256) ||
1456           (compression == JPEGCompression))
1457         {
1458           /*
1459             Truecolor image.
1460           */
1461           (void) WriteBlobString(image,PS3_DirectClass"\n");
1462           switch (compression)
1463           {
1464             case NoCompression:
1465             default:
1466             {
1467               (void) WriteBlobString(image,PS3_NoCompression"\n");
1468               break;
1469             }
1470             case RLECompression:
1471             {
1472               (void) WriteBlobString(image,PS3_RLECompression"\n");
1473               break;
1474             }
1475             case JPEGCompression:
1476             {
1477               (void) WriteBlobString(image,PS3_JPEGCompression"\n");
1478               break;
1479             }
1480             case LZWCompression:
1481             {
1482               (void) WriteBlobString(image,PS3_LZWCompression"\n");
1483               break;
1484             }
1485             case ZipCompression:
1486             {
1487               (void) WriteBlobString(image,PS3_ZipCompression"\n");
1488               break;
1489             }
1490           }
1491           /*
1492             Image data.
1493           */
1494           if (compression == JPEGCompression)
1495             status=InjectImageBlob(image_info,image,image,"jpeg",
1496               &image->exception);
1497           else
1498             {
1499               /*
1500                 Stream based compressions.
1501               */
1502               status=SerializeImage(image_info,image,&pixels,&length);
1503               if (status == MagickFalse)
1504                 {
1505                   (void) CloseBlob(image);
1506                   return(MagickFalse);
1507                 }
1508               switch (compression)
1509               {
1510                 case NoCompression:
1511                 default:
1512                 {
1513                   Ascii85Initialize(image);
1514                   for (i=0; i < (long) length; i++)
1515                     Ascii85Encode(image,pixels[i]);
1516                   Ascii85Flush(image);
1517                   status=MagickTrue;
1518                   break;
1519                 }
1520                 case RLECompression:
1521                 {
1522                   status=PackbitsEncodeImage(image,length,pixels);
1523                   break;
1524                 }
1525                 case LZWCompression:
1526                 {
1527                   status=LZWEncodeImage(image,length,pixels);
1528                   break;
1529                 }
1530                 case ZipCompression:
1531                 {
1532                   status=ZLIBEncodeImage(image,length,pixels);
1533                   break;
1534                 }
1535               }
1536               pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1537             }
1538           }
1539         else
1540           {
1541             /*
1542               Colormapped images.
1543             */
1544             (void) WriteBlobString(image,PS3_PseudoClass"\n");
1545             switch (compression)
1546             {
1547               case NoCompression:
1548               default:
1549               {
1550                 (void) WriteBlobString(image,PS3_NoCompression"\n");
1551                 break;
1552               }
1553               case JPEGCompression:
1554               {
1555                 (void) WriteBlobString(image,PS3_JPEGCompression"\n");
1556                 break;
1557               }
1558               case RLECompression:
1559               {
1560                 (void) WriteBlobString(image,PS3_RLECompression"\n");
1561                 break;
1562               }
1563               case LZWCompression:
1564               {
1565                 (void) WriteBlobString(image,PS3_LZWCompression"\n");
1566                 break;
1567               }
1568               case ZipCompression:
1569               {
1570                 (void) WriteBlobString(image,PS3_ZipCompression"\n");
1571                 break;
1572               }
1573             }
1574             /*
1575               Number of colors in color map.
1576             */
1577             (void) FormatMagickString(buffer,MaxTextExtent,"%lu\n",
1578               image->colors);
1579             (void) WriteBlobString(image,buffer);
1580             /*
1581               Color map - uncompressed.
1582             */
1583             if ((compression != NoCompression) &&
1584                 (compression != UndefinedCompression))
1585               {
1586                 for (i=0; i < (long) image->colors; i++)
1587                 {
1588                   pixel=ScaleQuantumToChar(image->colormap[i].red);
1589                   (void) WriteBlobByte(image,(unsigned char) pixel);
1590                   pixel=ScaleQuantumToChar(image->colormap[i].green);
1591                   (void) WriteBlobByte(image,(unsigned char) pixel);
1592                   pixel=ScaleQuantumToChar(image->colormap[i].blue);
1593                   (void) WriteBlobByte(image,(unsigned char) pixel);
1594                 }
1595               }
1596             else
1597               {
1598                 Ascii85Initialize(image);
1599                 for (i=0; i < (long) image->colors; i++)
1600                 {
1601                   pixel=ScaleQuantumToChar(image->colormap[i].red);
1602                   Ascii85Encode(image,(unsigned char) pixel);
1603                   pixel=ScaleQuantumToChar(image->colormap[i].green);
1604                   Ascii85Encode(image,(unsigned char) pixel);
1605                   pixel=ScaleQuantumToChar(image->colormap[i].blue);
1606                   Ascii85Encode(image,(unsigned char) pixel);
1607                 }
1608                 Ascii85Flush(image);
1609               }
1610             status=SerializeImageIndexes(image_info,image,&pixels,&length);
1611             if (status == MagickFalse)
1612               {
1613                 (void) CloseBlob(image);
1614                 return(MagickFalse);
1615               }
1616             switch (compression)
1617             {
1618               case NoCompression:
1619               default:
1620               {
1621                 Ascii85Initialize(image);
1622                 for (i=0; i < (long) length; i++)
1623                   Ascii85Encode(image,pixels[i]);
1624                 Ascii85Flush(image);
1625                 status=MagickTrue;
1626                 break;
1627               }
1628               case JPEGCompression:
1629               {
1630                 status=InjectImageBlob(image_info,image,image,"jpeg",
1631                   &image->exception);
1632                 break;
1633               }
1634               case RLECompression:
1635               {
1636                 status=PackbitsEncodeImage(image,length,pixels);
1637                 break;
1638               }
1639               case LZWCompression:
1640               {
1641                 status=LZWEncodeImage(image,length,pixels);
1642                 break;
1643               }
1644               case ZipCompression:
1645               {
1646                 status=ZLIBEncodeImage(image,length,pixels);
1647                 break;
1648               }
1649             }
1650             pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1651           }
1652     (void) WriteBlobByte(image,'\n');
1653     if (status == MagickFalse)
1654       {
1655         (void) CloseBlob(image);
1656         return(MagickFalse);
1657       }
1658     /*
1659       Update BeginData now that we know the data size.
1660     */
1661     length=(size_t) (TellBlob(image)-stop);
1662     stop=TellBlob(image);
1663     offset=SeekBlob(image,start,SEEK_SET);
1664     if (offset < 0)
1665       ThrowWriterException(CorruptImageError,"ImproperImageHeader");
1666     (void) FormatMagickString(buffer,MaxTextExtent,
1667       "%%%%BeginData:%13ld %s Bytes\n",(long) length,
1668       compression == NoCompression ? "ASCII" : "BINARY");
1669     (void) WriteBlobString(image,buffer);
1670     offset=SeekBlob(image,stop,SEEK_SET);
1671     (void) WriteBlobString(image,"%%EndData\n");
1672     /*
1673       End private dictionary if this an EPS.
1674     */
1675     if (LocaleCompare(image_info->magick,"PS3") != 0)
1676       (void) WriteBlobString(image,"end\n");
1677     (void) WriteBlobString(image,"%%PageTrailer\n");
1678     if (GetNextImageInList(image) == (Image *) NULL)
1679       break;
1680     image=SyncNextImageInList(image);
1681     status=SetImageProgress(image,SaveImagesTag,scene++,
1682       GetImageListLength(image));
1683     if (status == MagickFalse)
1684       break;
1685   } while (image_info->adjoin != MagickFalse);
1686   (void) WriteBlobString(image,"%%Trailer\n");
1687   if (page > 1)
1688     {
1689       (void) FormatMagickString(buffer,MaxTextExtent,
1690         "%%%%BoundingBox: %g %g %g %g\n",floor(bounds.x1+0.5),
1691         floor(bounds.y1+0.5),ceil(bounds.x2-0.5),ceil(bounds.y2-0.5));
1692       (void) WriteBlobString(image,buffer);
1693       (void) FormatMagickString(buffer,MaxTextExtent,
1694         "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1,
1695         bounds.x2,bounds.y2);
1696       (void) WriteBlobString(image,buffer);
1697     }
1698   (void) WriteBlobString(image,"%%EOF\n");
1699   (void) CloseBlob(image);
1700   return(MagickTrue);
1701 }