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