]> 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   assert(exception != (ExceptionInfo *) NULL);
875   assert(exception->signature == MagickSignature);
876   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
877   if (status == MagickFalse)
878     return(MagickFalse);
879   compression=image->compression;
880   if (image_info->compression != UndefinedCompression)
881     compression=image_info->compression;
882   switch (compression)
883   {
884     case FaxCompression:
885     case Group4Compression:
886     { 
887       if ((IsImageMonochrome(image,exception) == MagickFalse) ||
888           (image->matte != MagickFalse))
889         compression=RLECompression;
890       break;
891     }
892 #if !defined(MAGICKCORE_JPEG_DELEGATE)
893     case JPEGCompression:
894     {
895       compression=RLECompression;
896       (void) ThrowMagickException(exception,GetMagickModule(),
897         MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)",
898         image->filename);
899       break;
900     }
901 #endif
902 #if !defined(MAGICKCORE_ZLIB_DELEGATE)
903     case ZipCompression:
904     {
905       compression=RLECompression;
906       (void) ThrowMagickException(exception,GetMagickModule(),
907         MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)",
908         image->filename);
909       break;
910     }
911 #endif
912     default:
913       break;
914   }
915   (void) ResetMagickMemory(&bounds,0,sizeof(bounds));
916   page=0;
917   scene=0;
918   do
919   {
920     /*
921       Scale relative to dots-per-inch.
922     */
923     delta.x=DefaultResolution;
924     delta.y=DefaultResolution;
925     resolution.x=image->x_resolution;
926     resolution.y=image->y_resolution;
927     if ((resolution.x == 0.0) || (resolution.y == 0.0))
928       {
929         flags=ParseGeometry(PSDensityGeometry,&geometry_info);
930         resolution.x=geometry_info.rho;
931         resolution.y=geometry_info.sigma;
932         if ((flags & SigmaValue) == 0)
933           resolution.y=resolution.x;
934       }
935     if (image_info->density != (char *) NULL)
936       {
937         flags=ParseGeometry(image_info->density,&geometry_info);
938         resolution.x=geometry_info.rho;
939         resolution.y=geometry_info.sigma;
940         if ((flags & SigmaValue) == 0)
941           resolution.y=resolution.x;
942       }
943     if (image->units == PixelsPerCentimeterResolution)
944       {
945         resolution.x=(size_t) (100.0*2.54*resolution.x+0.5)/100.0;
946         resolution.y=(size_t) (100.0*2.54*resolution.y+0.5)/100.0;
947       }
948     SetGeometry(image,&geometry);
949     (void) FormatLocaleString(page_geometry,MaxTextExtent,"%.20gx%.20g",
950       (double) image->columns,(double) image->rows);
951     if (image_info->page != (char *) NULL)
952       (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent);
953     else
954       if ((image->page.width != 0) && (image->page.height != 0))
955         (void) FormatLocaleString(page_geometry,MaxTextExtent,
956           "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double)
957           image->page.height,(double) image->page.x,(double) image->page.y);
958       else
959         if ((image->gravity != UndefinedGravity) &&
960             (LocaleCompare(image_info->magick,"PS") == 0))
961           (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent);
962     (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent);
963     (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,
964       &geometry.width,&geometry.height);
965     scale.x=(double) (geometry.width*delta.x)/resolution.x;
966     geometry.width=(size_t) floor(scale.x+0.5);
967     scale.y=(double) (geometry.height*delta.y)/resolution.y;
968     geometry.height=(size_t) floor(scale.y+0.5);
969     (void) ParseAbsoluteGeometry(page_geometry,&media_info);
970     (void) ParseGravityGeometry(image,page_geometry,&page_info,exception);
971     if (image->gravity != UndefinedGravity)
972       {
973         geometry.x=(-page_info.x);
974         geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);
975       }
976     pointsize=12.0;
977     if (image_info->pointsize != 0.0)
978       pointsize=image_info->pointsize;
979     text_size=0;
980     value=GetImageProperty(image,"label");
981     if (value != (const char *) NULL)
982       text_size=(size_t) (MultilineCensus(value)*pointsize+12);
983     page++;
984     if (page == 1)
985       {
986         /*
987           Postscript header on the first page.
988         */
989         if (LocaleCompare(image_info->magick,"PS3") == 0)
990           (void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MaxTextExtent);
991         else
992           (void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n",
993             MaxTextExtent);
994         (void) WriteBlobString(image,buffer);
995         (void) FormatLocaleString(buffer,MaxTextExtent,
996           "%%%%Creator: ImageMagick %s\n",MagickLibVersionText);
997         (void) WriteBlobString(image,buffer);
998         (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Title: %s\n",
999           image->filename);
1000         (void) WriteBlobString(image,buffer);
1001         timer=time((time_t *) NULL);
1002         (void) FormatMagickTime(timer,MaxTextExtent,date);
1003         (void) FormatLocaleString(buffer,MaxTextExtent,
1004           "%%%%CreationDate: %s\n",date);
1005         (void) WriteBlobString(image,buffer);
1006         bounds.x1=(double) geometry.x;
1007         bounds.y1=(double) geometry.y;
1008         bounds.x2=(double) geometry.x+scale.x;
1009         bounds.y2=(double) geometry.y+scale.y+text_size;
1010         if ((image_info->adjoin != MagickFalse) &&
1011             (GetNextImageInList(image) != (Image *) NULL))
1012           {
1013             (void) WriteBlobString(image,"%%BoundingBox: (atend)\n");
1014             (void) WriteBlobString(image,"%%HiResBoundingBox: (atend)\n");
1015           }
1016         else
1017           {
1018             (void) FormatLocaleString(buffer,MaxTextExtent,
1019               "%%%%BoundingBox: %g %g %g %g\n",floor(bounds.x1+0.5),
1020               floor(bounds.y1+0.5),ceil(bounds.x2-0.5),ceil(bounds.y2-0.5));
1021             (void) WriteBlobString(image,buffer);
1022             (void) FormatLocaleString(buffer,MaxTextExtent,
1023               "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,
1024               bounds.y1,bounds.x2,bounds.y2);
1025             (void) WriteBlobString(image,buffer);
1026             if (image->colorspace == CMYKColorspace)
1027               (void) WriteBlobString(image,
1028                 "%%DocumentProcessColors: Cyan Magenta Yellow Black\n");
1029             else
1030               if (IsImageGray(image,exception) != MagickFalse)
1031                 (void) WriteBlobString(image,
1032                   "%%DocumentProcessColors: Black\n");
1033           }
1034         /*
1035           Font resources
1036         */
1037         value=GetImageProperty(image,"label");
1038         if (value != (const char *) NULL)
1039           (void) WriteBlobString(image,
1040             "%%DocumentNeededResources: font Helvetica\n");
1041         (void) WriteBlobString(image,"%%LanguageLevel: 3\n");
1042         /*
1043           Pages, orientation and order.
1044         */
1045         if (LocaleCompare(image_info->magick,"PS3") != 0)
1046           (void) WriteBlobString(image,"%%Pages: 1\n");
1047         else
1048           {
1049             (void) WriteBlobString(image,"%%Orientation: Portrait\n");
1050             (void) WriteBlobString(image,"%%PageOrder: Ascend\n");
1051             if (image_info->adjoin == MagickFalse)
1052               (void) CopyMagickString(buffer,"%%Pages: 1\n",MaxTextExtent);
1053             else
1054               (void) FormatLocaleString(buffer,MaxTextExtent,
1055                 "%%%%Pages: %.20g\n",(double) GetImageListLength(image));
1056             (void) WriteBlobString(image,buffer);
1057           }
1058         (void) WriteBlobString(image,"%%EndComments\n");
1059         /*
1060           The static postscript procedures prolog.
1061         */
1062         (void)WriteBlobString(image,"%%BeginProlog\n");
1063         for (q=PostscriptProlog; *q; q++)
1064         {
1065           (void) WriteBlobString(image,*q);
1066           (void) WriteBlobByte(image,'\n');
1067         }
1068         /*
1069           One label line for each line in label string.
1070         */
1071         value=GetImageProperty(image,"label");
1072         if (value != (const char *) NULL)
1073           {
1074               (void) WriteBlobString(image,"\n  %% Labels.\n  /Helvetica "
1075               " findfont pointsize scalefont setfont\n");
1076             for (i=(ssize_t) MultilineCensus(value)-1; i >= 0; i--)
1077             {
1078               (void) WriteBlobString(image,
1079                 "  currentfile buffer readline pop token pop\n");
1080               (void) FormatLocaleString(buffer,MaxTextExtent,
1081                 "  0 y %g add moveto show pop\n",i*pointsize+12);
1082               (void) WriteBlobString(image,buffer);
1083             }
1084           }
1085         /*
1086           The static postscript procedures epilog.
1087         */
1088         for (q=PostscriptEpilog; *q; q++)
1089         {
1090           (void) WriteBlobString(image,*q);
1091           (void) WriteBlobByte(image,'\n');
1092         }
1093         (void)WriteBlobString(image,"%%EndProlog\n");
1094       }
1095     (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Page: 1 %.20g\n",
1096       (double) page);
1097     (void) WriteBlobString(image,buffer);
1098     /*
1099       Page bounding box.
1100     */
1101     (void) FormatLocaleString(buffer,MaxTextExtent,
1102       "%%%%PageBoundingBox: %.20g %.20g %.20g %.20g\n",(double) geometry.x,
1103        (double) geometry.y,geometry.x+(double) geometry.width,geometry.y+
1104        (double) (geometry.height+text_size));
1105     (void) WriteBlobString(image,buffer);
1106     /*
1107       Page process colors if not RGB.
1108     */
1109     if (image->colorspace == CMYKColorspace)
1110       (void) WriteBlobString(image,
1111         "%%PageProcessColors: Cyan Magenta Yellow Black\n");
1112     else
1113       if (IsImageGray(image,exception) != MagickFalse)
1114         (void) WriteBlobString(image,"%%PageProcessColors: Black\n");
1115     /*
1116       Adjust document bounding box to bound page bounding box.
1117     */
1118     if ((double) geometry.x < bounds.x1)
1119       bounds.x1=(double) geometry.x;
1120     if ((double) geometry.y < bounds.y1)
1121       bounds.y1=(double) geometry.y;
1122     if ((double) (geometry.x+scale.x) > bounds.x2)
1123       bounds.x2=(double) geometry.x+scale.x;
1124     if ((double) (geometry.y+scale.y+text_size) > bounds.y2)
1125       bounds.y2=(double) geometry.y+scale.y+text_size;
1126     /*
1127       Page font resource if there's a label.
1128     */
1129     value=GetImageProperty(image,"label");
1130     if (value != (const char *) NULL)
1131       (void) WriteBlobString(image,"%%PageResources: font Helvetica\n");
1132     /*
1133       PS clipping path from Photoshop clipping path.
1134     */
1135     if ((image->clip_mask == (Image *) NULL) ||
1136         (LocaleNCompare("8BIM:",image->clip_mask->magick_filename,5) != 0))
1137       (void) WriteBlobString(image,"/ClipImage {} def\n");
1138     else
1139       {
1140         const char
1141           *value;
1142
1143         value=GetImageProperty(image,image->clip_mask->magick_filename);
1144         if (value == (const char *) NULL)
1145           return(MagickFalse);
1146         (void) WriteBlobString(image,value);
1147         (void) WriteBlobByte(image,'\n');
1148       }
1149     /*
1150       Push a dictionary for our own def's if this an EPS.
1151     */
1152     if (LocaleCompare(image_info->magick,"PS3") != 0)
1153       (void) WriteBlobString(image,"userdict begin\n");
1154     /*
1155       Image mask.
1156     */
1157     if ((image->matte != MagickFalse) &&
1158         (WritePS3MaskImage(image_info,image,compression) == MagickFalse))
1159       {
1160         (void) CloseBlob(image);
1161         return(MagickFalse);
1162       }
1163     /*
1164       Remember position of BeginData comment so we can update it.
1165     */
1166     start=TellBlob(image);
1167     (void) FormatLocaleString(buffer,MaxTextExtent,
1168       "%%%%BeginData:%13ld %s Bytes\n",0L,
1169       compression == NoCompression ? "ASCII" : "BINARY");
1170     (void) WriteBlobString(image,buffer);
1171     stop=TellBlob(image);
1172     (void) WriteBlobString(image,"DisplayImage\n");
1173     /*
1174       Translate, scale, and font point size.
1175     */
1176     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n%g %g\n%g\n",
1177       (double) geometry.x,(double) geometry.y,scale.x,scale.y,pointsize);
1178     (void) WriteBlobString(image,buffer);
1179     /*
1180       Output labels.
1181     */
1182     labels=(char **) NULL;
1183     value=GetImageProperty(image,"label");
1184     if (value != (const char *) NULL)
1185       labels=StringToList(value);
1186     if (labels != (char **) NULL)
1187       {
1188         for (i=0; labels[i] != (char *) NULL; i++)
1189         {
1190           if (compression != NoCompression)
1191             {
1192               for (j=0; labels[i][j] != '\0'; j++)
1193                 (void) WriteBlobByte(image,(unsigned char) labels[i][j]);
1194               (void) WriteBlobByte(image,'\n');
1195             }
1196           else
1197             {
1198               (void) WriteBlobString(image,"<~");
1199               Ascii85Initialize(image);
1200               for (j=0; labels[i][j] != '\0'; j++)
1201                 Ascii85Encode(image,(unsigned char) labels[i][j]);
1202               Ascii85Flush(image);
1203             }
1204           labels[i]=DestroyString(labels[i]);
1205         }
1206         labels=(char **) RelinquishMagickMemory(labels);
1207       }
1208     /*
1209       Photoshop clipping path active?
1210     */
1211     if ((image->clip_mask != (Image *) NULL) &&
1212         (LocaleNCompare("8BIM:",image->clip_mask->magick_filename,5) == 0))
1213         (void) WriteBlobString(image,"true\n");
1214       else
1215         (void) WriteBlobString(image,"false\n");
1216     /*
1217       Showpage for non-EPS.
1218     */
1219     (void) WriteBlobString(image, LocaleCompare(image_info->magick,"PS3") == 0 ?
1220       "true\n" : "false\n");
1221     /*
1222       Image columns, rows, and color space.
1223     */
1224     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n%s\n",
1225       (double) image->columns,(double) image->rows,image->colorspace ==
1226       CMYKColorspace ? PS3_CMYKColorspace : PS3_RGBColorspace);
1227     (void) WriteBlobString(image,buffer);
1228     /*
1229       Masked image?
1230     */
1231     (void) WriteBlobString(image,image->matte != MagickFalse ?
1232       "true\n" : "false\n");
1233     /*
1234       Render with imagemask operator?
1235     */
1236     option=GetImageOption(image_info,"ps3:imagemask");
1237     (void) WriteBlobString(image,((option != (const char *) NULL) &&
1238       (IsImageMonochrome(image,exception) != MagickFalse)) ?
1239       "true\n" : "false\n");
1240     /*
1241       Output pixel data.
1242     */
1243     pixels=(unsigned char *) NULL;
1244     length=0;
1245     if ((image_info->type != TrueColorType) &&
1246         (image_info->type != TrueColorMatteType) &&
1247         (image_info->type != ColorSeparationType) &&
1248         (image_info->type != ColorSeparationMatteType) &&
1249         (image->colorspace != CMYKColorspace) &&
1250         ((IsImageGray(image,exception) != MagickFalse) ||
1251          (IsImageMonochrome(image,exception) != MagickFalse)))
1252       {
1253         /*
1254           Gray images.
1255         */
1256         (void) WriteBlobString(image,PS3_PseudoClass"\n");
1257         switch (compression)
1258         {
1259           case NoCompression:
1260           default:
1261           {
1262             (void) WriteBlobString(image,PS3_NoCompression"\n");
1263             break;
1264           }
1265           case FaxCompression:
1266           case Group4Compression:
1267           {
1268             (void) WriteBlobString(image,PS3_FaxCompression"\n");
1269             break;
1270           }
1271           case JPEGCompression:
1272           {
1273             (void) WriteBlobString(image,PS3_JPEGCompression"\n");
1274             break;
1275           }
1276           case LZWCompression:
1277           {
1278             (void) WriteBlobString(image,PS3_LZWCompression"\n");
1279             break;
1280           }
1281           case RLECompression:
1282           {
1283             (void) WriteBlobString(image,PS3_RLECompression"\n");
1284             break;
1285           }
1286           case ZipCompression:
1287           {
1288             (void) WriteBlobString(image,PS3_ZipCompression"\n");
1289             break;
1290           }
1291         }
1292         /*
1293           Number of colors -- 0 for single component non-color mapped data.
1294         */
1295         (void) WriteBlobString(image,"0\n");
1296         /*
1297           1 bit or 8 bit components?
1298         */
1299         (void) FormatLocaleString(buffer,MaxTextExtent,"%d\n",
1300           IsImageMonochrome(image,exception) != MagickFalse ? 1 : 8);
1301         (void) WriteBlobString(image,buffer);
1302         /*
1303           Image data.
1304         */
1305         if (compression == JPEGCompression)
1306           status=InjectImageBlob(image_info,image,image,"jpeg",exception);
1307         else
1308           if ((compression == FaxCompression) ||
1309               (compression == Group4Compression))
1310             {
1311               if (LocaleCompare(CCITTParam,"0") == 0)
1312                 status=HuffmanEncodeImage(image_info,image,image);
1313               else
1314                 status=Huffman2DEncodeImage(image_info,image,image);
1315             }
1316           else
1317             {
1318               status=SerializeImageChannel(image_info,image,&pixels,&length);
1319               if (status == MagickFalse)
1320                 {
1321                   (void) CloseBlob(image);
1322                   return(MagickFalse);
1323                 }
1324               switch (compression)
1325               {
1326                 case NoCompression:
1327                 default:
1328                 {
1329                   Ascii85Initialize(image);
1330                   for (i=0; i < (ssize_t) length; i++)
1331                     Ascii85Encode(image,pixels[i]);
1332                   Ascii85Flush(image);
1333                   status=MagickTrue;
1334                   break;
1335                 }
1336                 case LZWCompression:
1337                 {
1338                   status=LZWEncodeImage(image,length,pixels);
1339                   break;
1340                 }
1341                 case RLECompression:
1342                 {
1343                   status=PackbitsEncodeImage(image,length,pixels);
1344                   break;
1345                 }
1346                 case ZipCompression:
1347                 {
1348                   status=ZLIBEncodeImage(image,length,pixels);
1349                   break;
1350                 }
1351               }
1352               pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1353             }
1354       }
1355     else
1356       if ((image->storage_class == DirectClass) || (image->colors > 256) ||
1357           (compression == JPEGCompression))
1358         {
1359           /*
1360             Truecolor image.
1361           */
1362           (void) WriteBlobString(image,PS3_DirectClass"\n");
1363           switch (compression)
1364           {
1365             case NoCompression:
1366             default:
1367             {
1368               (void) WriteBlobString(image,PS3_NoCompression"\n");
1369               break;
1370             }
1371             case RLECompression:
1372             {
1373               (void) WriteBlobString(image,PS3_RLECompression"\n");
1374               break;
1375             }
1376             case JPEGCompression:
1377             {
1378               (void) WriteBlobString(image,PS3_JPEGCompression"\n");
1379               break;
1380             }
1381             case LZWCompression:
1382             {
1383               (void) WriteBlobString(image,PS3_LZWCompression"\n");
1384               break;
1385             }
1386             case ZipCompression:
1387             {
1388               (void) WriteBlobString(image,PS3_ZipCompression"\n");
1389               break;
1390             }
1391           }
1392           /*
1393             Image data.
1394           */
1395           if (compression == JPEGCompression)
1396             status=InjectImageBlob(image_info,image,image,"jpeg",exception);
1397           else
1398             {
1399               /*
1400                 Stream based compressions.
1401               */
1402               status=SerializeImage(image_info,image,&pixels,&length);
1403               if (status == MagickFalse)
1404                 {
1405                   (void) CloseBlob(image);
1406                   return(MagickFalse);
1407                 }
1408               switch (compression)
1409               {
1410                 case NoCompression:
1411                 default:
1412                 {
1413                   Ascii85Initialize(image);
1414                   for (i=0; i < (ssize_t) length; i++)
1415                     Ascii85Encode(image,pixels[i]);
1416                   Ascii85Flush(image);
1417                   status=MagickTrue;
1418                   break;
1419                 }
1420                 case RLECompression:
1421                 {
1422                   status=PackbitsEncodeImage(image,length,pixels);
1423                   break;
1424                 }
1425                 case LZWCompression:
1426                 {
1427                   status=LZWEncodeImage(image,length,pixels);
1428                   break;
1429                 }
1430                 case ZipCompression:
1431                 {
1432                   status=ZLIBEncodeImage(image,length,pixels);
1433                   break;
1434                 }
1435               }
1436               pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1437             }
1438           }
1439         else
1440           {
1441             /*
1442               Colormapped images.
1443             */
1444             (void) WriteBlobString(image,PS3_PseudoClass"\n");
1445             switch (compression)
1446             {
1447               case NoCompression:
1448               default:
1449               {
1450                 (void) WriteBlobString(image,PS3_NoCompression"\n");
1451                 break;
1452               }
1453               case JPEGCompression:
1454               {
1455                 (void) WriteBlobString(image,PS3_JPEGCompression"\n");
1456                 break;
1457               }
1458               case RLECompression:
1459               {
1460                 (void) WriteBlobString(image,PS3_RLECompression"\n");
1461                 break;
1462               }
1463               case LZWCompression:
1464               {
1465                 (void) WriteBlobString(image,PS3_LZWCompression"\n");
1466                 break;
1467               }
1468               case ZipCompression:
1469               {
1470                 (void) WriteBlobString(image,PS3_ZipCompression"\n");
1471                 break;
1472               }
1473             }
1474             /*
1475               Number of colors in color map.
1476             */
1477             (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",
1478               (double) image->colors);
1479             (void) WriteBlobString(image,buffer);
1480             /*
1481               Color map - uncompressed.
1482             */
1483             if ((compression != NoCompression) &&
1484                 (compression != UndefinedCompression))
1485               {
1486                 for (i=0; i < (ssize_t) image->colors; i++)
1487                 {
1488                   pixel=ScaleQuantumToChar(image->colormap[i].red);
1489                   (void) WriteBlobByte(image,(unsigned char) pixel);
1490                   pixel=ScaleQuantumToChar(image->colormap[i].green);
1491                   (void) WriteBlobByte(image,(unsigned char) pixel);
1492                   pixel=ScaleQuantumToChar(image->colormap[i].blue);
1493                   (void) WriteBlobByte(image,(unsigned char) pixel);
1494                 }
1495               }
1496             else
1497               {
1498                 Ascii85Initialize(image);
1499                 for (i=0; i < (ssize_t) image->colors; i++)
1500                 {
1501                   pixel=ScaleQuantumToChar(image->colormap[i].red);
1502                   Ascii85Encode(image,(unsigned char) pixel);
1503                   pixel=ScaleQuantumToChar(image->colormap[i].green);
1504                   Ascii85Encode(image,(unsigned char) pixel);
1505                   pixel=ScaleQuantumToChar(image->colormap[i].blue);
1506                   Ascii85Encode(image,(unsigned char) pixel);
1507                 }
1508                 Ascii85Flush(image);
1509               }
1510             status=SerializeImageIndexes(image_info,image,&pixels,&length);
1511             if (status == MagickFalse)
1512               {
1513                 (void) CloseBlob(image);
1514                 return(MagickFalse);
1515               }
1516             switch (compression)
1517             {
1518               case NoCompression:
1519               default:
1520               {
1521                 Ascii85Initialize(image);
1522                 for (i=0; i < (ssize_t) length; i++)
1523                   Ascii85Encode(image,pixels[i]);
1524                 Ascii85Flush(image);
1525                 status=MagickTrue;
1526                 break;
1527               }
1528               case JPEGCompression:
1529               {
1530                 status=InjectImageBlob(image_info,image,image,"jpeg",exception);
1531                 break;
1532               }
1533               case RLECompression:
1534               {
1535                 status=PackbitsEncodeImage(image,length,pixels);
1536                 break;
1537               }
1538               case LZWCompression:
1539               {
1540                 status=LZWEncodeImage(image,length,pixels);
1541                 break;
1542               }
1543               case ZipCompression:
1544               {
1545                 status=ZLIBEncodeImage(image,length,pixels);
1546                 break;
1547               }
1548             }
1549             pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1550           }
1551     (void) WriteBlobByte(image,'\n');
1552     if (status == MagickFalse)
1553       {
1554         (void) CloseBlob(image);
1555         return(MagickFalse);
1556       }
1557     /*
1558       Update BeginData now that we know the data size.
1559     */
1560     length=(size_t) (TellBlob(image)-stop);
1561     stop=TellBlob(image);
1562     offset=SeekBlob(image,start,SEEK_SET);
1563     if (offset < 0)
1564       ThrowWriterException(CorruptImageError,"ImproperImageHeader");
1565     (void) FormatLocaleString(buffer,MaxTextExtent,
1566       "%%%%BeginData:%13ld %s Bytes\n",(long) length,
1567       compression == NoCompression ? "ASCII" : "BINARY");
1568     (void) WriteBlobString(image,buffer);
1569     offset=SeekBlob(image,stop,SEEK_SET);
1570     (void) WriteBlobString(image,"%%EndData\n");
1571     /*
1572       End private dictionary if this an EPS.
1573     */
1574     if (LocaleCompare(image_info->magick,"PS3") != 0)
1575       (void) WriteBlobString(image,"end\n");
1576     (void) WriteBlobString(image,"%%PageTrailer\n");
1577     if (GetNextImageInList(image) == (Image *) NULL)
1578       break;
1579     image=SyncNextImageInList(image);
1580     status=SetImageProgress(image,SaveImagesTag,scene++,
1581       GetImageListLength(image));
1582     if (status == MagickFalse)
1583       break;
1584   } while (image_info->adjoin != MagickFalse);
1585   (void) WriteBlobString(image,"%%Trailer\n");
1586   if (page > 1)
1587     {
1588       (void) FormatLocaleString(buffer,MaxTextExtent,
1589         "%%%%BoundingBox: %g %g %g %g\n",floor(bounds.x1+0.5),
1590         floor(bounds.y1+0.5),ceil(bounds.x2-0.5),ceil(bounds.y2-0.5));
1591       (void) WriteBlobString(image,buffer);
1592       (void) FormatLocaleString(buffer,MaxTextExtent,
1593         "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1,
1594         bounds.x2,bounds.y2);
1595       (void) WriteBlobString(image,buffer);
1596     }
1597   (void) WriteBlobString(image,"%%EOF\n");
1598   (void) CloseBlob(image);
1599   return(MagickTrue);
1600 }