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