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