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