]> granicus.if.org Git - imagemagick/blob - coders/ps2.c
74be992ffb936ae22bb88b7b07a0c5eb61449df5
[imagemagick] / coders / ps2.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            PPPP   SSSSS  22222                              %
7 %                            P   P  SS        22                              %
8 %                            PPPP    SSS    222                               %
9 %                            P         SS  22                                 %
10 %                            P      SSSSS  22222                              %
11 %                                                                             %
12 %                                                                             %
13 %                      Write Postscript Level II Format                       %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                John Cristy                                  %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2009 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 \f
39 /*
40   Include declarations.
41 */
42 #include "magick/studio.h"
43 #include "magick/blob.h"
44 #include "magick/blob-private.h"
45 #include "magick/cache.h"
46 #include "magick/color.h"
47 #include "magick/color-private.h"
48 #include "magick/compress.h"
49 #include "magick/constitute.h"
50 #include "magick/draw.h"
51 #include "magick/exception.h"
52 #include "magick/exception-private.h"
53 #include "magick/geometry.h"
54 #include "magick/image.h"
55 #include "magick/image-private.h"
56 #include "magick/list.h"
57 #include "magick/magick.h"
58 #include "magick/memory_.h"
59 #include "magick/monitor.h"
60 #include "magick/monitor-private.h"
61 #include "magick/monitor-private.h"
62 #include "magick/option.h"
63 #include "magick/resource_.h"
64 #include "magick/property.h"
65 #include "magick/quantum-private.h"
66 #include "magick/static.h"
67 #include "magick/string_.h"
68 #include "magick/module.h"
69 #include "magick/utility.h"
70 #if defined(MAGICKCORE_TIFF_DELEGATE)
71 #if defined(MAGICKCORE_HAVE_TIFFCONF_H)
72 #include "tiffconf.h"
73 #endif
74 #include "tiffio.h"
75 #define CCITTParam  "-1"
76 #else
77 #define CCITTParam  "0"
78 #endif
79 \f
80 /*
81   Forward declarations.
82 */
83 static MagickBooleanType
84   WritePS2Image(const ImageInfo *,Image *);
85 \f
86 /*
87 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
88 %                                                                             %
89 %                                                                             %
90 %                                                                             %
91 %   R e g i s t e r P S 2 I m a g e                                           %
92 %                                                                             %
93 %                                                                             %
94 %                                                                             %
95 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
96 %
97 %  RegisterPS2Image() adds properties for the PS2 image format to
98 %  the list of supported formats.  The properties include the image format
99 %  tag, a method to read and/or write the format, whether the format
100 %  supports the saving of more than one frame to the same file or blob,
101 %  whether the format supports native in-memory I/O, and a brief
102 %  description of the format.
103 %
104 %  The format of the RegisterPS2Image method is:
105 %
106 %      unsigned long RegisterPS2Image(void)
107 %
108 */
109 ModuleExport unsigned long RegisterPS2Image(void)
110 {
111   MagickInfo
112     *entry;
113
114   entry=SetMagickInfo("EPS2");
115   entry->encoder=(EncodeImageHandler *) WritePS2Image;
116   entry->adjoin=MagickFalse;
117   entry->seekable_stream=MagickTrue;
118   entry->description=ConstantString("Level II Encapsulated PostScript");
119   entry->module=ConstantString("PS2");
120   (void) RegisterMagickInfo(entry);
121   entry=SetMagickInfo("PS2");
122   entry->encoder=(EncodeImageHandler *) WritePS2Image;
123   entry->seekable_stream=MagickTrue;
124   entry->description=ConstantString("Level II PostScript");
125   entry->module=ConstantString("PS2");
126   (void) RegisterMagickInfo(entry);
127   return(MagickImageCoderSignature);
128 }
129 \f
130 /*
131 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
132 %                                                                             %
133 %                                                                             %
134 %                                                                             %
135 %   U n r e g i s t e r P S 2 I m a g e                                       %
136 %                                                                             %
137 %                                                                             %
138 %                                                                             %
139 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
140 %
141 %  UnregisterPS2Image() removes format registrations made by the
142 %  PS2 module from the list of supported formats.
143 %
144 %  The format of the UnregisterPS2Image method is:
145 %
146 %      UnregisterPS2Image(void)
147 %
148 */
149 ModuleExport void UnregisterPS2Image(void)
150 {
151   (void) UnregisterMagickInfo("EPS2");
152   (void) UnregisterMagickInfo("PS2");
153 }
154 \f
155 /*
156 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
157 %                                                                             %
158 %                                                                             %
159 %                                                                             %
160 %   W r i t e P S 2 I m a g e                                                 %
161 %                                                                             %
162 %                                                                             %
163 %                                                                             %
164 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
165 %
166 %  WritePS2Image translates an image to encapsulated Postscript
167 %  Level II for printing.  If the supplied geometry is null, the image is
168 %  centered on the Postscript page.  Otherwise, the image is positioned as
169 %  specified by the geometry.
170 %
171 %  The format of the WritePS2Image method is:
172 %
173 %      MagickBooleanType WritePS2Image(const ImageInfo *image_info,Image *image)
174 %
175 %  A description of each parameter follows:
176 %
177 %    o image_info: the image info.
178 %
179 %    o image: the image.
180 %
181 */
182
183 #if defined(MAGICKCORE_TIFF_DELEGATE)
184 static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info,
185   Image *image,Image *inject_image)
186 {
187   char
188     filename[MaxTextExtent];
189
190   FILE
191     *file;
192
193   Image
194     *huffman_image;
195
196   ImageInfo
197     *write_info;
198
199   int
200     unique_file;
201
202   MagickBooleanType
203     status;
204
205   register long
206     i;
207
208   ssize_t
209     count;
210
211   TIFF
212     *tiff;
213
214   uint16
215     fillorder;
216
217   uint32
218     *byte_count,
219     strip_size;
220
221   unsigned char
222     *buffer;
223
224   /*
225     Write image as CCITTFax4 TIFF image to a temporary file.
226   */
227   assert(image_info != (const ImageInfo *) NULL);
228   assert(image_info->signature == MagickSignature);
229   assert(image != (Image *) NULL);
230   assert(image->signature == MagickSignature);
231   if (image->debug != MagickFalse)
232     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
233   assert(inject_image != (Image *) NULL);
234   assert(inject_image->signature == MagickSignature);
235   huffman_image=CloneImage(inject_image,0,0,MagickTrue,&image->exception);
236   if (huffman_image == (Image *) NULL)
237     return(MagickFalse);
238   file=(FILE *) NULL;
239   unique_file=AcquireUniqueFileResource(filename);
240   if (unique_file != -1)
241     file=fdopen(unique_file,"wb"); 
242   if ((unique_file == -1) || (file == (FILE *) NULL))
243     {
244       ThrowFileException(&image->exception,FileOpenError,
245         "UnableToCreateTemporaryFile",filename);
246       return(MagickFalse);
247     }
248   (void) FormatMagickString(huffman_image->filename,MaxTextExtent,"tiff:%s",
249     filename);
250   write_info=CloneImageInfo(image_info);
251   SetImageInfoFile(write_info,file);
252   write_info->compression=Group4Compression;
253   (void) SetImageOption(write_info,"quantum:polarity","min-is-white");
254   status=WriteImage(write_info,huffman_image);
255   (void) fflush(file);
256   write_info=DestroyImageInfo(write_info);
257   if (status == MagickFalse)
258     return(MagickFalse);
259   tiff=TIFFOpen(filename,"rb");
260   if (tiff == (TIFF *) NULL)
261     {
262       huffman_image=DestroyImage(huffman_image);
263       (void) fclose(file);
264       (void) RelinquishUniqueFileResource(filename);
265       ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile",
266         image_info->filename);
267       return(MagickFalse);
268     }
269   /*
270     Allocate raw strip buffer.
271   */
272   byte_count=0;
273   (void) TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count);
274   strip_size=byte_count[0];
275   for (i=1; i < (long) TIFFNumberOfStrips(tiff); i++)
276     if (byte_count[i] > strip_size)
277       strip_size=byte_count[i];
278   buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
279     sizeof(*buffer));
280   if (buffer == (unsigned char *) NULL)
281     {
282       TIFFClose(tiff);
283       huffman_image=DestroyImage(huffman_image);
284       (void) fclose(file);
285       (void) RelinquishUniqueFileResource(filename);
286       ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
287         image_info->filename);
288     }
289   /*
290     Compress runlength encoded to 2D Huffman pixels.
291   */
292   fillorder=FILLORDER_LSB2MSB;
293   (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&fillorder);
294   for (i=0; i < (long) TIFFNumberOfStrips(tiff); i++)
295   {
296     count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,(long)
297       byte_count[i]);
298     if (fillorder == FILLORDER_LSB2MSB)
299       TIFFReverseBits(buffer,(unsigned long) count);
300     (void) WriteBlob(image,(size_t) count,buffer);
301   }
302   buffer=(unsigned char *) RelinquishMagickMemory(buffer);
303   TIFFClose(tiff);
304   huffman_image=DestroyImage(huffman_image);
305   (void) fclose(file);
306   (void) RelinquishUniqueFileResource(filename);
307   return(MagickTrue);
308 }
309 #else
310 static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info,
311   Image *image,Image *inject_image)
312 {
313   assert(image_info != (const ImageInfo *) NULL);
314   assert(image_info->signature == MagickSignature);
315   assert(image != (Image *) NULL);
316   assert(image->signature == MagickSignature);
317   if (image->debug != MagickFalse)
318     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
319   assert(inject_image != (Image *) NULL);
320   assert(inject_image->signature == MagickSignature);
321   (void) ThrowMagickException(&image->exception,GetMagickModule(),
322     MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (TIFF)",
323     image->filename);
324   return(MagickFalse);
325 }
326 #endif
327
328 static MagickBooleanType WritePS2Image(const ImageInfo *image_info,Image *image)
329 {
330   static const char
331     *PostscriptProlog[]=
332     {
333       "%%%%BeginProlog",
334       "%%",
335       "%% Display a color image.  The image is displayed in color on",
336       "%% Postscript viewers or printers that support color, otherwise",
337       "%% it is displayed as grayscale.",
338       "%%",
339       "/DirectClassImage",
340       "{",
341       "  %%",
342       "  %% Display a DirectClass image.",
343       "  %%",
344       "  colorspace 0 eq",
345       "  {",
346       "    /DeviceRGB setcolorspace",
347       "    <<",
348       "      /ImageType 1",
349       "      /Width columns",
350       "      /Height rows",
351       "      /BitsPerComponent 8",
352       "      /Decode [0 1 0 1 0 1]",
353       "      /ImageMatrix [columns 0 0 rows neg 0 rows]",
354       "      compression 0 gt",
355       "      { /DataSource pixel_stream /%s filter }",
356       "      { /DataSource pixel_stream /%s filter } ifelse",
357       "    >> image",
358       "  }",
359       "  {",
360       "    /DeviceCMYK setcolorspace",
361       "    <<",
362       "      /ImageType 1",
363       "      /Width columns",
364       "      /Height rows",
365       "      /BitsPerComponent 8",
366       "      /Decode [1 0 1 0 1 0 1 0]",
367       "      /ImageMatrix [columns 0 0 rows neg 0 rows]",
368       "      compression 0 gt",
369       "      { /DataSource pixel_stream /%s filter }",
370       "      { /DataSource pixel_stream /%s filter } ifelse",
371       "    >> image",
372       "  } ifelse",
373       "} bind def",
374       "",
375       "/PseudoClassImage",
376       "{",
377       "  %%",
378       "  %% Display a PseudoClass image.",
379       "  %%",
380       "  %% Parameters:",
381       "  %%   colors: number of colors in the colormap.",
382       "  %%",
383       "  currentfile buffer readline pop",
384       "  token pop /colors exch def pop",
385       "  colors 0 eq",
386       "  {",
387       "    %%",
388       "    %% Image is grayscale.",
389       "    %%",
390       "    currentfile buffer readline pop",
391       "    token pop /bits exch def pop",
392       "    /DeviceGray setcolorspace",
393       "    <<",
394       "      /ImageType 1",
395       "      /Width columns",
396       "      /Height rows",
397       "      /BitsPerComponent bits",
398       "      /Decode [0 1]",
399       "      /ImageMatrix [columns 0 0 rows neg 0 rows]",
400       "      compression 0 gt",
401       "      { /DataSource pixel_stream /%s filter }",
402       "      {",
403       "        /DataSource pixel_stream /%s filter",
404       "        <<",
405       "           /K "CCITTParam,
406       "           /Columns columns",
407       "           /Rows rows",
408       "        >> /CCITTFaxDecode filter",
409       "      } ifelse",
410       "    >> image",
411       "  }",
412       "  {",
413       "    %%",
414       "    %% Parameters:",
415       "    %%   colormap: red, green, blue color packets.",
416       "    %%",
417       "    /colormap colors 3 mul string def",
418       "    currentfile colormap readhexstring pop pop",
419       "    currentfile buffer readline pop",
420       "    [ /Indexed /DeviceRGB colors 1 sub colormap ] setcolorspace",
421       "    <<",
422       "      /ImageType 1",
423       "      /Width columns",
424       "      /Height rows",
425       "      /BitsPerComponent 8",
426       "      /Decode [0 255]",
427       "      /ImageMatrix [columns 0 0 rows neg 0 rows]",
428       "      compression 0 gt",
429       "      { /DataSource pixel_stream /%s filter }",
430       "      { /DataSource pixel_stream /%s filter } ifelse",
431       "    >> image",
432       "  } ifelse",
433       "} bind def",
434       "",
435       "/DisplayImage",
436       "{",
437       "  %%",
438       "  %% Display a DirectClass or PseudoClass image.",
439       "  %%",
440       "  %% Parameters:",
441       "  %%   x & y translation.",
442       "  %%   x & y scale.",
443       "  %%   label pointsize.",
444       "  %%   image label.",
445       "  %%   image columns & rows.",
446       "  %%   class: 0-DirectClass or 1-PseudoClass.",
447       "  %%   colorspace: 0-RGB or 1-CMYK.",
448       "  %%   compression: 0-RLECompression or 1-NoCompression.",
449       "  %%   hex color packets.",
450       "  %%",
451       "  gsave",
452       "  /buffer 512 string def",
453       "  /pixel_stream currentfile def",
454       "",
455       "  currentfile buffer readline pop",
456       "  token pop /x exch def",
457       "  token pop /y exch def pop",
458       "  x y translate",
459       "  currentfile buffer readline pop",
460       "  token pop /x exch def",
461       "  token pop /y exch def pop",
462       "  currentfile buffer readline pop",
463       "  token pop /pointsize exch def pop",
464       "  /Helvetica findfont pointsize scalefont setfont",
465       (char *) NULL
466     },
467     *PostscriptEpilog[]=
468     {
469       "  x y scale",
470       "  currentfile buffer readline pop",
471       "  token pop /columns exch def",
472       "  token pop /rows exch def pop",
473       "  currentfile buffer readline pop",
474       "  token pop /class exch def pop",
475       "  currentfile buffer readline pop",
476       "  token pop /colorspace exch def pop",
477       "  currentfile buffer readline pop",
478       "  token pop /compression exch def pop",
479       "  class 0 gt { PseudoClassImage } { DirectClassImage } ifelse",
480       (char *) NULL
481     };
482
483   char
484     buffer[MaxTextExtent],
485     date[MaxTextExtent],
486     page_geometry[MaxTextExtent],
487     **labels;
488
489   CompressionType
490     compression;
491
492   const char
493     **q,
494     *value;
495
496   double
497     pointsize;
498
499   GeometryInfo
500     geometry_info;
501
502   long
503     j,
504     y;
505
506   MagickOffsetType
507     scene,
508     start,
509     stop;
510
511   MagickBooleanType
512     progress,
513     status;
514
515   MagickOffsetType
516     offset;
517
518   MagickSizeType
519     number_pixels;
520
521   MagickStatusType
522     flags;
523
524   PointInfo
525     delta,
526     resolution,
527     scale;
528
529   RectangleInfo
530     geometry,
531     media_info,
532     page_info;
533
534   register const IndexPacket
535     *indexes;
536
537   register const PixelPacket
538     *p;
539
540   register long
541     x;
542
543   register long
544     i;
545
546   SegmentInfo
547     bounds;
548
549   size_t
550     length;
551
552   time_t
553     timer;
554
555   unsigned char
556     *pixels;
557
558   unsigned long
559     page,
560     text_size;
561
562   /*
563     Open output image file.
564   */
565   assert(image_info != (const ImageInfo *) NULL);
566   assert(image_info->signature == MagickSignature);
567   assert(image != (Image *) NULL);
568   assert(image->signature == MagickSignature);
569   if (image->debug != MagickFalse)
570     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
571   status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
572   if (status == MagickFalse)
573     return(status);
574   compression=image->compression;
575   if (image_info->compression != UndefinedCompression)
576     compression=image_info->compression;
577   switch (compression)
578   {
579 #if !defined(MAGICKCORE_JPEG_DELEGATE)
580     case JPEGCompression:
581     {
582       compression=RLECompression;
583       (void) ThrowMagickException(&image->exception,GetMagickModule(),
584         MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)",
585         image->filename);
586       break;
587     }
588 #endif
589     default:
590       break;
591   }
592   (void) ResetMagickMemory(&bounds,0,sizeof(bounds));
593   page=1;
594   scene=0;
595   do
596   {
597     /*
598       Scale relative to dots-per-inch.
599     */
600     delta.x=DefaultResolution;
601     delta.y=DefaultResolution;
602     resolution.x=image->x_resolution;
603     resolution.y=image->y_resolution;
604     if ((resolution.x == 0.0) || (resolution.y == 0.0))
605       {
606         flags=ParseGeometry(PSDensityGeometry,&geometry_info);
607         resolution.x=geometry_info.rho;
608         resolution.y=geometry_info.sigma;
609         if ((flags & SigmaValue) == 0)
610           resolution.y=resolution.x;
611       }
612     if (image_info->density != (char *) NULL)
613       {
614         flags=ParseGeometry(image_info->density,&geometry_info);
615         resolution.x=geometry_info.rho;
616         resolution.y=geometry_info.sigma;
617         if ((flags & SigmaValue) == 0)
618           resolution.y=resolution.x;
619       }
620     if (image->units == PixelsPerCentimeterResolution)
621       {
622         resolution.x*=2.54;
623         resolution.y*=2.54;
624       }
625     SetGeometry(image,&geometry);
626     (void) FormatMagickString(page_geometry,MaxTextExtent,"%lux%lu",
627       image->columns,image->rows);
628     if (image_info->page != (char *) NULL)
629       (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent);
630     else
631       if ((image->page.width != 0) && (image->page.height != 0))
632         (void) FormatMagickString(page_geometry,MaxTextExtent,"%lux%lu%+ld%+ld",
633           image->page.width,image->page.height,image->page.x,image->page.y);
634       else
635         if ((image->gravity != UndefinedGravity) &&
636             (LocaleCompare(image_info->magick,"PS") == 0))
637           (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent);
638     (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent);
639     (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,
640       &geometry.width,&geometry.height);
641     scale.x=(double) (geometry.width*delta.x)/resolution.x;
642     geometry.width=(unsigned long) (scale.x+0.5);
643     scale.y=(double) (geometry.height*delta.y)/resolution.y;
644     geometry.height=(unsigned long) (scale.y+0.5);
645     (void) ParseAbsoluteGeometry(page_geometry,&media_info);
646     (void) ParseGravityGeometry(image,page_geometry,&page_info,
647       &image->exception);
648     if (image->gravity != UndefinedGravity)
649       {
650         geometry.x=(-page_info.x);
651         geometry.y=(long) (media_info.height+page_info.y-image->rows);
652       }
653     pointsize=12.0;
654     if (image_info->pointsize != 0.0)
655       pointsize=image_info->pointsize;
656     text_size=0;
657     value=GetImageProperty(image,"label");
658     if (value != (const char *) NULL)
659       text_size=(unsigned long) (MultilineCensus(value)*pointsize+12);
660     if (page == 1)
661       {
662         /*
663           Output Postscript header.
664         */
665         if (LocaleCompare(image_info->magick,"PS2") == 0)
666           (void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MaxTextExtent);
667         else
668           (void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n",
669             MaxTextExtent);
670         (void) WriteBlobString(image,buffer);
671         (void) WriteBlobString(image,"%%Creator: (ImageMagick)\n");
672         (void) FormatMagickString(buffer,MaxTextExtent,"%%%%Title: (%s)\n",
673           image->filename);
674         (void) WriteBlobString(image,buffer);
675         timer=time((time_t *) NULL);
676         (void) FormatMagickTime(timer,MaxTextExtent,date);
677         (void) FormatMagickString(buffer,MaxTextExtent,
678           "%%%%CreationDate: (%s)\n",date);
679         (void) WriteBlobString(image,buffer);
680         bounds.x1=(double) geometry.x;
681         bounds.y1=(double) geometry.y;
682         bounds.x2=(double) geometry.x+geometry.width;
683         bounds.y2=(double) geometry.y+geometry.height+text_size;
684         if ((image_info->adjoin != MagickFalse) &&
685             (GetNextImageInList(image) != (Image *) NULL))
686           (void) CopyMagickString(buffer,"%%BoundingBox: (atend)\n",
687             MaxTextExtent);
688         else
689           {
690             (void) FormatMagickString(buffer,MaxTextExtent,
691               "%%%%BoundingBox: %ld %ld %ld %ld\n",(long) (bounds.x1+0.5),
692               (long) (bounds.y1+0.5),
693               (long) (bounds.x2+0.5),(long) (bounds.y2+0.5));
694             (void) WriteBlobString(image,buffer);
695             (void) FormatMagickString(buffer,MaxTextExtent,
696               "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1,
697               bounds.x2,bounds.y2);
698           }
699         (void) WriteBlobString(image,buffer);
700         value=GetImageProperty(image,"label");
701         if (value != (const char *) NULL)
702           (void) WriteBlobString(image,
703             "%%DocumentNeededResources: font Helvetica\n");
704         (void) WriteBlobString(image,"%%LanguageLevel: 2\n");
705         if (LocaleCompare(image_info->magick,"PS2") != 0)
706           (void) WriteBlobString(image,"%%Pages: 1\n");
707         else
708           {
709             (void) WriteBlobString(image,"%%Orientation: Portrait\n");
710             (void) WriteBlobString(image,"%%PageOrder: Ascend\n");
711             if (image_info->adjoin == MagickFalse)
712               (void) CopyMagickString(buffer,"%%Pages: 1\n",MaxTextExtent);
713             else
714               (void) FormatMagickString(buffer,MaxTextExtent,"%%%%Pages: %lu\n",
715                 (unsigned long) GetImageListLength(image));
716             (void) WriteBlobString(image,buffer);
717           }
718         (void) WriteBlobString(image,"%%EndComments\n");
719         (void) WriteBlobString(image,"\n%%BeginDefaults\n");
720         (void) WriteBlobString(image,"%%EndDefaults\n\n");
721         /*
722           Output Postscript commands.
723         */
724         for (q=PostscriptProlog; *q; q++)
725         {
726           switch (compression)
727           {
728             case NoCompression:
729             {
730               (void) FormatMagickString(buffer,MaxTextExtent,*q,
731                 "ASCII85Decode");
732               break;
733             }
734             case JPEGCompression:
735             {
736               (void) FormatMagickString(buffer,MaxTextExtent,*q,"DCTDecode");
737               break;
738             }
739             case LZWCompression:
740             {
741               (void) FormatMagickString(buffer,MaxTextExtent,*q,"LZWDecode");
742               break;
743             }
744             case FaxCompression:
745             case Group4Compression:
746             {
747               (void) FormatMagickString(buffer,MaxTextExtent,*q,
748                 "ASCII85Decode");
749               break;
750             }
751             default:
752             {
753               (void) FormatMagickString(buffer,MaxTextExtent,*q,
754                 "RunLengthDecode");
755               break;
756             }
757           }
758           (void) WriteBlobString(image,buffer);
759           (void) WriteBlobByte(image,'\n');
760         }
761         value=GetImageProperty(image,"label");
762         if (value != (const char *) NULL)
763           for (j=(long) MultilineCensus(value)-1; j >= 0; j--)
764           {
765             (void) WriteBlobString(image,"  /label 512 string def\n");
766             (void) WriteBlobString(image,"  currentfile label readline pop\n");
767             (void) FormatMagickString(buffer,MaxTextExtent,
768               "  0 y %g add moveto label show pop\n",j*pointsize+12);
769             (void) WriteBlobString(image,buffer);
770           }
771         for (q=PostscriptEpilog; *q; q++)
772         {
773           (void) FormatMagickString(buffer,MaxTextExtent,"%s\n",*q);
774           (void) WriteBlobString(image,buffer);
775         }
776         if (LocaleCompare(image_info->magick,"PS2") == 0)
777           (void) WriteBlobString(image,"  showpage\n");
778         (void) WriteBlobString(image,"} bind def\n");
779         (void) WriteBlobString(image,"%%EndProlog\n");
780       }
781     (void) FormatMagickString(buffer,MaxTextExtent,"%%%%Page:  1 %lu\n",page++);
782     (void) WriteBlobString(image,buffer);
783     (void) FormatMagickString(buffer,MaxTextExtent,
784       "%%%%PageBoundingBox: %ld %ld %ld %ld\n",geometry.x,geometry.y,
785       geometry.x+(long) geometry.width,geometry.y+(long)
786       (geometry.height+text_size));
787     (void) WriteBlobString(image,buffer);
788     if ((double) geometry.x < bounds.x1)
789       bounds.x1=(double) geometry.x;
790     if ((double) geometry.y < bounds.y1)
791       bounds.y1=(double) geometry.y;
792     if ((double) (geometry.x+geometry.width-1) > bounds.x2)
793       bounds.x2=(double) geometry.x+geometry.width-1;
794     if ((double) (geometry.y+(geometry.height+text_size)-1) > bounds.y2)
795       bounds.y2=(double) geometry.y+(geometry.height+text_size)-1;
796     value=GetImageProperty(image,"label");
797     if (value != (const char *) NULL)
798       (void) WriteBlobString(image,"%%PageResources: font Times-Roman\n");
799     if (LocaleCompare(image_info->magick,"PS2") != 0)
800       (void) WriteBlobString(image,"userdict begin\n");
801     start=TellBlob(image);
802     (void) FormatMagickString(buffer,MaxTextExtent,
803       "%%%%BeginData:%13ld %s Bytes\n",0L,
804       compression == NoCompression ? "ASCII" : "Binary");
805     (void) WriteBlobString(image,buffer);
806     stop=TellBlob(image);
807     (void) WriteBlobString(image,"DisplayImage\n");
808     /*
809       Output image data.
810     */
811     (void) FormatMagickString(buffer,MaxTextExtent,"%ld %ld\n%g %g\n%f\n",
812       geometry.x,geometry.y,scale.x,scale.y,pointsize);
813     (void) WriteBlobString(image,buffer);
814     labels=(char **) NULL;
815     value=GetImageProperty(image,"label");
816     if (value != (const char *) NULL)
817       labels=StringToList(value);
818     if (labels != (char **) NULL)
819       {
820         for (i=0; labels[i] != (char *) NULL; i++)
821         {
822           (void) FormatMagickString(buffer,MaxTextExtent,"%s \n",
823             labels[i]);
824           (void) WriteBlobString(image,buffer);
825           labels[i]=DestroyString(labels[i]);
826         }
827         labels=(char **) RelinquishMagickMemory(labels);
828       }
829     number_pixels=(MagickSizeType) image->columns*image->rows;
830     if (number_pixels != (MagickSizeType) ((size_t) number_pixels))
831       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
832     if ((compression == FaxCompression) || (compression == Group4Compression) ||
833         ((image_info->type != TrueColorType) &&
834          (IsGrayImage(image,&image->exception) != MagickFalse)))
835       {
836         (void) FormatMagickString(buffer,MaxTextExtent,"%lu %lu\n1\n%d\n",
837           image->columns,image->rows,(int)
838           (image->colorspace == CMYKColorspace));
839         (void) WriteBlobString(image,buffer);
840         (void) FormatMagickString(buffer,MaxTextExtent,"%d\n",
841           (int) ((compression != FaxCompression) &&
842            (compression != Group4Compression)));
843         (void) WriteBlobString(image,buffer);
844         (void) WriteBlobString(image,"0\n");
845         (void) FormatMagickString(buffer,MaxTextExtent,"%d\n",
846            (compression == FaxCompression) ||
847            (compression == Group4Compression) ? 1 : 8);
848         (void) WriteBlobString(image,buffer);
849         switch (compression)
850         {
851           case FaxCompression:
852           case Group4Compression:
853           {
854             if (LocaleCompare(CCITTParam,"0") == 0)
855               {
856                 (void) HuffmanEncodeImage(image_info,image,image);
857                 break;
858               }
859             (void) Huffman2DEncodeImage(image_info,image,image);
860             break;
861           }
862           case JPEGCompression:
863           {
864             status=InjectImageBlob(image_info,image,image,"jpeg",
865               &image->exception);
866             if (status == MagickFalse)
867               ThrowWriterException(CoderError,image->exception.reason);
868             break;
869           }
870           case RLECompression:
871           default:
872           {
873             register unsigned char
874               *q;
875
876             /*
877               Allocate pixel array.
878             */
879             length=(size_t) number_pixels;
880             pixels=(unsigned char *) AcquireQuantumMemory(length,
881               sizeof(*pixels));
882             if (pixels == (unsigned char *) NULL)
883               ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
884             /*
885               Dump Runlength encoded pixels.
886             */
887             q=pixels;
888             for (y=0; y < (long) image->rows; y++)
889             {
890               p=GetVirtualPixels(image,0,y,image->columns,1,
891                 &image->exception);
892               if (p == (const PixelPacket *) NULL)
893                 break;
894               for (x=0; x < (long) image->columns; x++)
895               {
896                 *q++=ScaleQuantumToChar(PixelIntensityToQuantum(p));
897                 p++;
898               }
899               progress=SetImageProgress(image,SaveImageTag,y,image->rows);
900               if (progress == MagickFalse)
901                 break;
902             }
903             length=(size_t) (q-pixels);
904             if (compression == LZWCompression)
905               status=LZWEncodeImage(image,length,pixels);
906             else
907               status=PackbitsEncodeImage(image,length,pixels);
908             pixels=(unsigned char *) RelinquishMagickMemory(pixels);
909             if (status == MagickFalse)
910               {
911                 (void) CloseBlob(image);
912                 return(MagickFalse);
913               }
914             break;
915           }
916           case NoCompression:
917           {
918             /*
919               Dump uncompressed PseudoColor packets.
920             */
921             Ascii85Initialize(image);
922             for (y=0; y < (long) image->rows; y++)
923             {
924               p=GetVirtualPixels(image,0,y,image->columns,1,
925                 &image->exception);
926               if (p == (const PixelPacket *) NULL)
927                 break;
928               for (x=0; x < (long) image->columns; x++)
929               {
930                 Ascii85Encode(image,
931                   ScaleQuantumToChar(PixelIntensityToQuantum(p)));
932                 p++;
933               }
934               progress=SetImageProgress(image,SaveImageTag,y,image->rows);
935               if (progress == MagickFalse)
936                 break;
937             }
938             Ascii85Flush(image);
939             break;
940           }
941         }
942       }
943     else
944       if ((image->storage_class == DirectClass) || (image->colors > 256) ||
945           (compression == JPEGCompression) || (image->matte != MagickFalse))
946         {
947           (void) FormatMagickString(buffer,MaxTextExtent,"%lu %lu\n0\n%d\n",
948             image->columns,image->rows,(int)
949             (image->colorspace == CMYKColorspace));
950           (void) WriteBlobString(image,buffer);
951           (void) FormatMagickString(buffer,MaxTextExtent,"%d\n",
952             (int) (compression == NoCompression));
953           (void) WriteBlobString(image,buffer);
954           switch (compression)
955           {
956             case JPEGCompression:
957             {
958               status=InjectImageBlob(image_info,image,image,"jpeg",
959                 &image->exception);
960               if (status == MagickFalse)
961                 ThrowWriterException(CoderError,image->exception.reason);
962               break;
963             }
964             case RLECompression:
965             default:
966             {
967               register unsigned char
968                 *q;
969
970               /*
971                 Allocate pixel array.
972               */
973               length=(size_t) number_pixels;
974               pixels=(unsigned char *) AcquireQuantumMemory(length,
975                 4*sizeof(*pixels));
976               if (pixels == (unsigned char *) NULL)
977                 ThrowWriterException(ResourceLimitError,
978                   "MemoryAllocationFailed");
979               /*
980                 Dump Packbit encoded pixels.
981               */
982               q=pixels;
983               for (y=0; y < (long) image->rows; y++)
984               {
985                 p=GetVirtualPixels(image,0,y,image->columns,1,
986                   &image->exception);
987                 if (p == (const PixelPacket *) NULL)
988                   break;
989                 indexes=GetVirtualIndexQueue(image);
990                 for (x=0; x < (long) image->columns; x++)
991                 {
992                   if ((image->matte != MagickFalse) &&
993                       (p->opacity == (Quantum) TransparentOpacity))
994                     {
995                       *q++=ScaleQuantumToChar((Quantum) QuantumRange);
996                       *q++=ScaleQuantumToChar((Quantum) QuantumRange);
997                       *q++=ScaleQuantumToChar((Quantum) QuantumRange);
998                     }
999                   else
1000                     if (image->colorspace != CMYKColorspace)
1001                       {
1002                         *q++=ScaleQuantumToChar(p->red);
1003                         *q++=ScaleQuantumToChar(p->green);
1004                         *q++=ScaleQuantumToChar(p->blue);
1005                       }
1006                     else
1007                       {
1008                         *q++=ScaleQuantumToChar(p->red);
1009                         *q++=ScaleQuantumToChar(p->green);
1010                         *q++=ScaleQuantumToChar(p->blue);
1011                         *q++=ScaleQuantumToChar(indexes[x]);
1012                       }
1013                   p++;
1014                 }
1015                 progress=SetImageProgress(image,SaveImageTag,y,image->rows);
1016                 if (progress == MagickFalse)
1017                   break;
1018               }
1019               length=(size_t) (q-pixels);
1020               if (compression == LZWCompression)
1021                 status=LZWEncodeImage(image,length,pixels);
1022               else
1023                 status=PackbitsEncodeImage(image,length,pixels);
1024               if (status == MagickFalse)
1025                 {
1026                   (void) CloseBlob(image);
1027                   return(MagickFalse);
1028                 }
1029               pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1030               break;
1031             }
1032             case NoCompression:
1033             {
1034               /*
1035                 Dump uncompressed DirectColor packets.
1036               */
1037               Ascii85Initialize(image);
1038               for (y=0; y < (long) image->rows; y++)
1039               {
1040                 p=GetVirtualPixels(image,0,y,image->columns,1,
1041                   &image->exception);
1042                 if (p == (const PixelPacket *) NULL)
1043                   break;
1044                 indexes=GetVirtualIndexQueue(image);
1045                 for (x=0; x < (long) image->columns; x++)
1046                 {
1047                   if ((image->matte != MagickFalse) &&
1048                       (p->opacity == (Quantum) TransparentOpacity))
1049                     {
1050                       Ascii85Encode(image,ScaleQuantumToChar((Quantum)
1051                         QuantumRange));
1052                       Ascii85Encode(image,ScaleQuantumToChar((Quantum)
1053                         QuantumRange));
1054                       Ascii85Encode(image,ScaleQuantumToChar((Quantum)
1055                         QuantumRange));
1056                     }
1057                   else
1058                     if (image->colorspace != CMYKColorspace)
1059                       {
1060                         Ascii85Encode(image,ScaleQuantumToChar(p->red));
1061                         Ascii85Encode(image,ScaleQuantumToChar(p->green));
1062                         Ascii85Encode(image,ScaleQuantumToChar(p->blue));
1063                       }
1064                     else
1065                       {
1066                         Ascii85Encode(image,ScaleQuantumToChar(p->red));
1067                         Ascii85Encode(image,ScaleQuantumToChar(p->green));
1068                         Ascii85Encode(image,ScaleQuantumToChar(p->blue));
1069                         Ascii85Encode(image,ScaleQuantumToChar(indexes[x]));
1070                       }
1071                   p++;
1072                 }
1073                 progress=SetImageProgress(image,SaveImageTag,y,image->rows);
1074                 if (progress == MagickFalse)
1075                   break;
1076               }
1077               Ascii85Flush(image);
1078               break;
1079             }
1080           }
1081         }
1082       else
1083         {
1084           /*
1085             Dump number of colors and colormap.
1086           */
1087           (void) FormatMagickString(buffer,MaxTextExtent,"%lu %lu\n1\n%d\n",
1088             image->columns,image->rows,(int)
1089             (image->colorspace == CMYKColorspace));
1090           (void) WriteBlobString(image,buffer);
1091           (void) FormatMagickString(buffer,MaxTextExtent,"%d\n",
1092             (int) (compression == NoCompression));
1093           (void) WriteBlobString(image,buffer);
1094           (void) FormatMagickString(buffer,MaxTextExtent,"%lu\n",image->colors);
1095           (void) WriteBlobString(image,buffer);
1096           for (i=0; i < (long) image->colors; i++)
1097           {
1098             (void) FormatMagickString(buffer,MaxTextExtent,"%02X%02X%02X\n",
1099               ScaleQuantumToChar(image->colormap[i].red),
1100               ScaleQuantumToChar(image->colormap[i].green),
1101               ScaleQuantumToChar(image->colormap[i].blue));
1102             (void) WriteBlobString(image,buffer);
1103           }
1104           switch (compression)
1105           {
1106             case RLECompression:
1107             default:
1108             {
1109               register unsigned char
1110                 *q;
1111
1112               /*
1113                 Allocate pixel array.
1114               */
1115               length=(size_t) number_pixels;
1116               pixels=(unsigned char *) AcquireQuantumMemory(length,
1117                 sizeof(*pixels));
1118               if (pixels == (unsigned char *) NULL)
1119                 ThrowWriterException(ResourceLimitError,
1120                   "MemoryAllocationFailed");
1121               /*
1122                 Dump Runlength encoded pixels.
1123               */
1124               q=pixels;
1125               for (y=0; y < (long) image->rows; y++)
1126               {
1127                 p=GetVirtualPixels(image,0,y,image->columns,1,
1128                   &image->exception);
1129                 if (p == (const PixelPacket *) NULL)
1130                   break;
1131                 indexes=GetVirtualIndexQueue(image);
1132                 for (x=0; x < (long) image->columns; x++)
1133                   *q++=(unsigned char) indexes[x];
1134                 progress=SetImageProgress(image,SaveImageTag,y,image->rows);
1135                 if (progress == MagickFalse)
1136                   break;
1137               }
1138               length=(size_t) (q-pixels);
1139               if (compression == LZWCompression)
1140                 status=LZWEncodeImage(image,length,pixels);
1141               else
1142                 status=PackbitsEncodeImage(image,length,pixels);
1143               pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1144               if (status == MagickFalse)
1145                 {
1146                   (void) CloseBlob(image);
1147                   return(MagickFalse);
1148                 }
1149               break;
1150             }
1151             case NoCompression:
1152             {
1153               /*
1154                 Dump uncompressed PseudoColor packets.
1155               */
1156               Ascii85Initialize(image);
1157               for (y=0; y < (long) image->rows; y++)
1158               {
1159                 p=GetVirtualPixels(image,0,y,image->columns,1,
1160                   &image->exception);
1161                 if (p == (const PixelPacket *) NULL)
1162                   break;
1163                 indexes=GetVirtualIndexQueue(image);
1164                 for (x=0; x < (long) image->columns; x++)
1165                   Ascii85Encode(image,(unsigned char) indexes[x]);
1166                 progress=SetImageProgress(image,SaveImageTag,y,image->rows);
1167                 if (progress == MagickFalse)
1168                   break;
1169               }
1170               Ascii85Flush(image);
1171               break;
1172             }
1173           }
1174         }
1175     (void) WriteBlobByte(image,'\n');
1176     length=(size_t) (TellBlob(image)-stop);
1177     stop=TellBlob(image);
1178     offset=SeekBlob(image,start,SEEK_SET);
1179     if (offset < 0)
1180       ThrowWriterException(CorruptImageError,"ImproperImageHeader");
1181     (void) FormatMagickString(buffer,MaxTextExtent,
1182       "%%%%BeginData:%13ld %s Bytes\n",(long) length,
1183       compression == NoCompression ? "ASCII" : "Binary");
1184     (void) WriteBlobString(image,buffer);
1185     offset=SeekBlob(image,stop,SEEK_SET);
1186     (void) WriteBlobString(image,"%%EndData\n");
1187     if (LocaleCompare(image_info->magick,"PS2") != 0)
1188       (void) WriteBlobString(image,"end\n");
1189     (void) WriteBlobString(image,"%%PageTrailer\n");
1190     if (GetNextImageInList(image) == (Image *) NULL)
1191       break;
1192     image=SyncNextImageInList(image);
1193     status=SetImageProgress(image,SaveImagesTag,scene++,
1194       GetImageListLength(image));
1195     if (status == MagickFalse)
1196       break;
1197   } while (image_info->adjoin != MagickFalse);
1198   (void) WriteBlobString(image,"%%Trailer\n");
1199   if (page > 1)
1200     {
1201       (void) FormatMagickString(buffer,MaxTextExtent,
1202         "%%%%BoundingBox: %ld %ld %ld %ld\n",(long) (bounds.x1+0.5),
1203         (long) (bounds.y1+0.5),(long) (bounds.x2+0.5),(long) (bounds.y2+0.5));
1204       (void) WriteBlobString(image,buffer);
1205       (void) FormatMagickString(buffer,MaxTextExtent,
1206         "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1,bounds.x2,
1207         bounds.y2);
1208       (void) WriteBlobString(image,buffer);
1209     }
1210   (void) WriteBlobString(image,"%%EOF\n");
1211   (void) CloseBlob(image);
1212   return(MagickTrue);
1213 }