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