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