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