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