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