Commit 3cce97c9f for imagemagick.org

commit 3cce97c9f0405998cfa09176efaca827bb717c18
Author: Cristy <urban-warrior@imagemagick.org>
Date:   Sat Nov 28 18:22:43 2026 -0500

    SerializeImageChannel() and SerializeImageIndexes() now check for size overflow

diff --git a/coders/ps3.c b/coders/ps3.c
index 2355edb31..4f88889e4 100644
--- a/coders/ps3.c
+++ b/coders/ps3.c
@@ -49,6 +49,7 @@
 #include "MagickCore/channel.h"
 #include "MagickCore/color.h"
 #include "MagickCore/color-private.h"
+#include "MagickCore/colorspace.h"
 #include "MagickCore/colorspace-private.h"
 #include "MagickCore/compress.h"
 #include "MagickCore/constitute.h"
@@ -61,6 +62,7 @@
 #include "MagickCore/list.h"
 #include "MagickCore/magick.h"
 #include "MagickCore/memory_.h"
+#include "MagickCore/memory-private.h"
 #include "MagickCore/module.h"
 #include "MagickCore/monitor.h"
 #include "MagickCore/monitor-private.h"
@@ -71,7 +73,6 @@
 #include "MagickCore/resource_.h"
 #include "MagickCore/static.h"
 #include "MagickCore/string_.h"
-#include "MagickCore/module.h"
 #include "MagickCore/timer-private.h"
 #include "MagickCore/token.h"
 #include "MagickCore/utility.h"
@@ -137,13 +138,13 @@ ModuleExport size_t RegisterPS3Image(void)
   entry->encoder=(EncodeImageHandler *) WritePS3Image;
   entry->mime_type=ConstantString("application/postscript");
   entry->flags|=CoderEncoderSeekableStreamFlag;
-  entry->flags^=CoderBlobSupportFlag;
+  entry->flags&=~CoderBlobSupportFlag;
   (void) RegisterMagickInfo(entry);
   entry=AcquireMagickInfo("PS3","PS3","Level III PostScript");
   entry->encoder=(EncodeImageHandler *) WritePS3Image;
   entry->mime_type=ConstantString("application/postscript");
   entry->flags|=CoderEncoderSeekableStreamFlag;
-  entry->flags^=CoderBlobSupportFlag;
+  entry->flags&=~CoderBlobSupportFlag;
   (void) RegisterMagickInfo(entry);
   return(MagickImageCoderSignature);
 }
@@ -216,23 +217,18 @@ static inline void FilenameToTitle(const char *filename,char *title,

   if (extent == 0)
     return;
-  for (i=0; (filename[i] != '\0') && ((offset+1) < (ssize_t) extent); i++)
+  /*
+    Invariant: there is always room left to close every open parenthesis.
+  */
+  for (i=0; (filename[i] != '\0') && ((offset+1+depth) < (ssize_t) extent); i++)
   {
     unsigned char
-      c = filename[i];
+      c = (unsigned char) filename[i];

     /*
-      Only allow printable ASCII.
-    */
-    if ((c < 32) || (c > 126))
-      {
-        title[offset++]='_';
-        continue;
-      }
-    /*
-      Percent signs break DSC parsing.
+      Only allow printable ASCII; percent signs break DSC parsing.
     */
-    if (c == '%')
+    if ((c < 32) || (c > 126) || (c == '%'))
       {
         title[offset++]='_';
         continue;
@@ -242,8 +238,13 @@ static inline void FilenameToTitle(const char *filename,char *title,
     */
     if (c == '(')
       {
-        depth++;
-        title[offset++] = '(';
+        if ((offset+2+depth) < (ssize_t) extent)
+          {
+            depth++;
+            title[offset++]='(';
+          }
+        else
+          title[offset++]='_';
         continue;
       }
     if (c == ')')
@@ -255,17 +256,15 @@ static inline void FilenameToTitle(const char *filename,char *title,
             depth--;
             title[offset++]=')';
           }
-         continue;
-     }
-    /*
-      Everything else is allowed.
-    */
-    title[offset++]=c;
+        continue;
+      }
+    title[offset++]=(char) c;
   }
   /*
     If parentheses remain unbalanced, close them.
   */
-  while ((depth > 0) && ((offset+1) < (ssize_t) extent)) {
+  while (depth > 0)
+  {
     title[offset++]=')';
     depth--;
   }
@@ -274,10 +273,69 @@ static inline void FilenameToTitle(const char *filename,char *title,
     Ensure non-empty result.
   */
   if (offset == 0)
-    {
-      (void) CopyMagickString(title,"Untitled",extent-1);
-      title[extent-1]='\0';
-    }
+    (void) CopyMagickString(title,"Untitled",extent);
+}
+
+static inline MagickBooleanType PS3IsBinary(const CompressionType compression)
+{
+  switch (compression)
+  {
+    case FaxCompression:
+    case Group4Compression:
+    case JPEGCompression:
+    case LZWCompression:
+    case RLECompression:
+    case ZipCompression:
+      return(MagickTrue);
+    default:
+      return(MagickFalse);
+  }
+}
+
+static void WritePS3Label(Image *image,const char *label)
+{
+  char
+    octal[8];
+
+  const unsigned char
+    *p;
+
+  size_t
+    extent,
+    width;
+
+  /*
+    Emit one label as a 7-bit clean PostScript string on a single line.  The
+    line must fit the 512 byte readline buffer used by the prolog.
+  */
+  extent=2;
+  (void) WriteBlobByte(image,'(');
+  for (p=(const unsigned char *) label; *p != '\0'; p++)
+  {
+    if ((*p == '(') || (*p == ')') || (*p == '\\'))
+      width=2;
+    else
+      width=((*p < 32) || (*p > 126)) ? 4 : 1;
+    if ((extent+width) > 510)
+      break;
+    if (width == 1)
+      (void) WriteBlobByte(image,*p);
+    else
+      if (width == 2)
+        {
+          (void) WriteBlobByte(image,'\\');
+          (void) WriteBlobByte(image,*p);
+        }
+      else
+        {
+          (void) FormatLocaleString(octal,sizeof(octal),"\\%03o",(unsigned int)
+            *p);
+          (void) WriteBlobString(image,octal);
+        }
+    extent+=width;
+  }
+  (void) WriteBlobByte(image,')');
+  (void) WriteBlobByte(image,'\n');
 }

 static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info,
@@ -356,7 +414,10 @@ static MagickBooleanType SerializeImage(const ImageInfo *image_info,
   {
     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
     if (p == (const Quantum *) NULL)
-      break;
+      {
+        status=MagickFalse;
+        break;
+      }
     if (image->colorspace != CMYKColorspace)
       for (x=0; x < (ssize_t) image->columns; x++)
       {
@@ -420,7 +481,8 @@ static MagickBooleanType SerializeImageChannel(const ImageInfo *image_info,
   status=MagickTrue;
   pack=SetImageMonochrome(image,exception) == MagickFalse ? 1UL : 8UL;
   padded_columns=((image->columns+pack-1)/pack)*pack;
-  *length=(size_t) padded_columns*image->rows/pack;
+  if (HeapOverflowSanityCheckGetSize(padded_columns/pack,image->rows,length) != MagickFalse)
+    ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
   *pixel_info=AcquireVirtualMemory(*length,sizeof(*q));
   if (*pixel_info == (MemoryInfo *) NULL)
     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
@@ -429,7 +491,10 @@ static MagickBooleanType SerializeImageChannel(const ImageInfo *image_info,
   {
     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
     if (p == (const Quantum *) NULL)
-      break;
+      {
+        status=MagickFalse;
+        break;
+      }
     if (pack == 1)
       for (x=0; x < (ssize_t) image->columns; x++)
       {
@@ -443,15 +508,17 @@ static MagickBooleanType SerializeImageChannel(const ImageInfo *image_info,
         {
           bit=(unsigned char) 0x00;
           if (x < (ssize_t) image->columns)
-            bit=(unsigned char) (GetPixelLuma(image,p) == (double)
-              TransparentAlpha ? 0x01 : 0x00);
-          code=(code << 1)+bit;
+            {
+              bit=(unsigned char) (GetPixelLuma(image,p) == (double)
+                TransparentAlpha ? 0x01 : 0x00);
+              p+=(ptrdiff_t) GetPixelChannels(image);
+            }
+          code=(unsigned char) ((code << 1)+bit);
           if (((x+1) % (ssize_t) pack) == 0)
             {
               *q++=code;
               code='\0';
             }
-          p+=(ptrdiff_t) GetPixelChannels(image);
         }
       }
     status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
@@ -487,7 +554,8 @@ static MagickBooleanType SerializeImageIndexes(const ImageInfo *image_info,
   if (IsEventLogging() != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   status=MagickTrue;
-  *length=(size_t) image->columns*image->rows;
+  if (HeapOverflowSanityCheckGetSize((size_t) image->columns,image->rows,length) != MagickFalse)
+    ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
   *pixel_info=AcquireVirtualMemory(*length,sizeof(*q));
   if (*pixel_info == (MemoryInfo *) NULL)
     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
@@ -496,7 +564,10 @@ static MagickBooleanType SerializeImageIndexes(const ImageInfo *image_info,
   {
     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
     if (p == (const Quantum *) NULL)
-      break;
+      {
+        status=MagickFalse;
+        break;
+      }
     for (x=0; x < (ssize_t) image->columns; x++)
     {
       *q++=(unsigned char) ((ssize_t) GetPixelIndex(image,p));
@@ -516,7 +587,7 @@ static MagickBooleanType SerializeImageIndexes(const ImageInfo *image_info,
 }

 static MagickBooleanType WritePS3MaskImage(const ImageInfo *image_info,
-  Image *image,const CompressionType compression,ExceptionInfo *exception)
+  Image *image,CompressionType compression,ExceptionInfo *exception)
 {
   char
     buffer[MagickPathExtent];
@@ -528,6 +599,7 @@ static MagickBooleanType WritePS3MaskImage(const ImageInfo *image_info,
     status;

   MagickOffsetType
+    end,
     offset,
     start,
     stop;
@@ -549,6 +621,8 @@ static MagickBooleanType WritePS3MaskImage(const ImageInfo *image_info,
   if (IsEventLogging() != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   status=MagickTrue;
+  if (compression == JPEGCompression)
+    compression=NoCompression;  /* the mask is never JPEG encoded */
   /*
     Note BeginData DSC comment for update later.
   */
@@ -556,8 +630,8 @@ static MagickBooleanType WritePS3MaskImage(const ImageInfo *image_info,
   if (start < 0)
     ThrowWriterException(CorruptImageError,"ImproperImageHeader");
   (void) FormatLocaleString(buffer,MagickPathExtent,
-    "%%%%BeginData:%13ld %s Bytes\n",0L,compression == NoCompression ?
-    "ASCII" : "BINARY");
+    "%%%%BeginData:%13ld %s Bytes\n",0L,PS3IsBinary(compression) !=
+    MagickFalse ? "BINARY" : "ASCII");
   (void) WriteBlobString(image,buffer);
   stop=TellBlob(image);
   if (stop < 0)
@@ -613,9 +687,19 @@ static MagickBooleanType WritePS3MaskImage(const ImageInfo *image_info,
   (void) WriteBlobString(image,"/ReusableStreamDecode filter\n");
   mask_image=SeparateImage(image,AlphaChannel,exception);
   if (mask_image == (Image *) NULL)
-    ThrowWriterException(CoderError,exception->reason);
-  (void) SetImageType(mask_image,BilevelType,exception);
-  (void) SetImageType(mask_image,PaletteType,exception);
+    {
+      (void) CloseBlob(image);
+      return(MagickFalse);
+    }
+  status=SetImageType(mask_image,BilevelType,exception);
+  if (status != MagickFalse)
+    status=SetImageType(mask_image,PaletteType,exception);
+  if (status == MagickFalse)
+    {
+      mask_image=DestroyImage(mask_image);
+      (void) CloseBlob(image);
+      return(MagickFalse);
+    }
   mask_image->alpha_trait=UndefinedPixelTrait;
   pixels=(unsigned char *) NULL;
   length=0;
@@ -635,8 +719,10 @@ static MagickBooleanType WritePS3MaskImage(const ImageInfo *image_info,
     case FaxCompression:
     case Group4Compression:
     {
-      if ((compression == FaxCompression) ||
-          (LocaleCompare(CCITTParam,"0") == 0))
+      /*
+        The encoding must match the /K value (CCITTParam) of the prolog.
+      */
+      if (LocaleCompare(CCITTParam,"0") == 0)
         status=HuffmanEncodeImage(image_info,image,mask_image,exception);
       else
         status=Huffman2DEncodeImage(image_info,image,mask_image,exception);
@@ -677,17 +763,20 @@ static MagickBooleanType WritePS3MaskImage(const ImageInfo *image_info,
     }
   }
   mask_image=DestroyImage(mask_image);
+  if (status == MagickFalse)
+    return(MagickFalse);
   (void) WriteBlobByte(image,'\n');
-  length=(size_t) (TellBlob(image)-stop);
-  stop=TellBlob(image);
-  if (stop < 0)
+  end=TellBlob(image);
+  if (end < 0)
     ThrowWriterException(CorruptImageError,"ImproperImageHeader");
+  length=(size_t) (end-stop);
+  stop=end;
   offset=SeekBlob(image,start,SEEK_SET);
   if (offset < 0)
     ThrowWriterException(CorruptImageError,"ImproperImageHeader");
   (void) FormatLocaleString(buffer,MagickPathExtent,
     "%%%%BeginData:%13ld %s Bytes\n",(long) length,
-    compression == NoCompression ? "ASCII" : "BINARY");
+    PS3IsBinary(compression) != MagickFalse ? "BINARY" : "ASCII");
   (void) WriteBlobString(image,buffer);
   offset=SeekBlob(image,stop,SEEK_SET);
   if (offset < 0)
@@ -910,6 +999,7 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
     status;

   MagickOffsetType
+    end,
     offset,
     scene,
     start,
@@ -942,8 +1032,7 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
     text_size;

   ssize_t
-    i,
-    j;
+    i;

   time_t
     timer;
@@ -972,7 +1061,7 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
   {
     case FaxCompression:
     case Group4Compression:
-    {
+    {
       if ((SetImageMonochrome(image,exception) == MagickFalse) ||
           (image->alpha_trait != UndefinedPixelTrait))
         compression=RLECompression;
@@ -1007,7 +1096,12 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
   number_scenes=GetImageListLength(image);
   do
   {
+    CompressionType
+      page_compression;
+
     MagickBooleanType
+      clip_path,
+      gray_path,
       is_gray;

     /*
@@ -1078,7 +1172,24 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
     if (value != (const char *) NULL)
       text_size=(size_t) (MultilineCensus(value)*pointsize+12);
     page++;
+    if ((image->colorspace != CMYKColorspace) &&
+        (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse))
+      (void) TransformImageColorspace(image,sRGBColorspace,exception);
     is_gray=IdentifyImageCoderGray(image,exception);
+    gray_path=((image_info->type != TrueColorType) &&
+      (image_info->type != TrueColorAlphaType) &&
+      (image_info->type != ColorSeparationType) &&
+      (image_info->type != ColorSeparationAlphaType) &&
+      (image->colorspace != CMYKColorspace) &&
+      (is_gray != MagickFalse)) ? MagickTrue : MagickFalse;
+    /*
+      CCITT data is only emitted for gray images; elsewhere it is written as
+      ASCII85 (the prolog is told "no compression").
+    */
+    page_compression=compression;
+    if ((gray_path == MagickFalse) && ((compression == FaxCompression) ||
+        (compression == Group4Compression)))
+      page_compression=NoCompression;
     if (page == 1)
       {
         char
@@ -1229,17 +1340,20 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
     /*
       PS clipping path from Photoshop clipping path.
     */
-    if (((image->channels & WriteMaskChannel) != 0) ||
-        (LocaleNCompare("8BIM:",image->magick_filename,5) != 0))
-      (void) WriteBlobString(image,"/ClipImage {} def\n");
-    else
+    clip_path=MagickFalse;
+    if (((image->channels & WriteMaskChannel) != 0) &&
+        (LocaleNCompare("8BIM:",image->magick_filename,5) == 0))
       {
         value=GetImageProperty(image,image->magick_filename,exception);
-        if (value == (const char *) NULL)
-          return(MagickFalse);
-        (void) WriteBlobString(image,value);
-        (void) WriteBlobByte(image,'\n');
+        if (value != (const char *) NULL)
+          {
+            (void) WriteBlobString(image,value);
+            (void) WriteBlobByte(image,'\n');
+            clip_path=MagickTrue;
+          }
       }
+    if (clip_path == MagickFalse)
+      (void) WriteBlobString(image,"/ClipImage {} def\n");
     /*
       Push a dictionary for our own def's if this an EPS.
     */
@@ -1249,7 +1363,7 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
       Image mask.
     */
     if ((image->alpha_trait != UndefinedPixelTrait) &&
-        (WritePS3MaskImage(image_info,image,compression,exception) == MagickFalse))
+        (WritePS3MaskImage(image_info,image,page_compression,exception) == MagickFalse))
       {
         (void) CloseBlob(image);
         return(MagickFalse);
@@ -1262,7 +1376,7 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
       ThrowWriterException(CorruptImageError,"ImproperImageHeader");
     (void) FormatLocaleString(buffer,MagickPathExtent,
       "%%%%BeginData:%13ld %s Bytes\n",0L,
-      compression == NoCompression ? "ASCII" : "BINARY");
+      PS3IsBinary(page_compression) != MagickFalse ? "BINARY" : "ASCII");
     (void) WriteBlobString(image,buffer);
     stop=TellBlob(image);
     if (stop < 0)
@@ -1285,46 +1399,16 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
       {
         for (i=0; labels[i] != (char *) NULL; i++)
         {
-          char
-            *escape;
-
-          escape=EscapeParenthesis(labels[i],510,exception);
-          if (compression != NoCompression)
-            {
-              for (j=0; escape[j] != '\0'; j++)
-                (void) WriteBlobByte(image,(unsigned char) escape[j]);
-              (void) WriteBlobByte(image,'\n');
-            }
-          else
-            {
-              (void) WriteBlobString(image,"<~");
-              status=Ascii85EncodeImage(image,strlen(escape),
-                (const unsigned char *) escape,exception);
-            }
-          escape=DestroyString(escape);
+          WritePS3Label(image,labels[i]);
           labels[i]=DestroyString(labels[i]);
-          if (status == MagickFalse)
-            {
-              for (i++; labels[i] != (char *) NULL; i++)
-                labels[i]=DestroyString(labels[i]);
-              break;
-            }
         }
         labels=(char **) RelinquishMagickMemory(labels);
-        if (status == MagickFalse)
-          {
-            (void) CloseBlob(image);
-            return(MagickFalse);
-          }
       }
     /*
       Photoshop clipping path active?
     */
-    if (((image->channels & WriteMaskChannel) != 0) &&
-        (LocaleNCompare("8BIM:",image->magick_filename,5) == 0))
-        (void) WriteBlobString(image,"true\n");
-      else
-        (void) WriteBlobString(image,"false\n");
+    (void) WriteBlobString(image,clip_path != MagickFalse ? "true\n" :
+      "false\n");
     /*
       Showpage for non-EPS.
     */
@@ -1354,18 +1438,13 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
     */
     pixels=(unsigned char *) NULL;
     length=0;
-    if ((image_info->type != TrueColorType) &&
-        (image_info->type != TrueColorAlphaType) &&
-        (image_info->type != ColorSeparationType) &&
-        (image_info->type != ColorSeparationAlphaType) &&
-        (image->colorspace != CMYKColorspace) &&
-        (is_gray != MagickFalse))
+    if (gray_path != MagickFalse)
       {
         /*
           Gray images.
         */
         (void) WriteBlobString(image,PS3_PseudoClass"\n");
-        switch (compression)
+        switch (page_compression)
         {
           default:
           {
@@ -1412,11 +1491,11 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
         /*
           Image data.
         */
-        if (compression == JPEGCompression)
+        if (page_compression == JPEGCompression)
           status=InjectImageBlob(image_info,image,image,"jpeg",exception);
         else
-          if ((compression == FaxCompression) ||
-              (compression == Group4Compression))
+          if ((page_compression == FaxCompression) ||
+              (page_compression == Group4Compression))
             {
               if (LocaleCompare(CCITTParam,"0") == 0)
                 status=HuffmanEncodeImage(image_info,image,image,exception);
@@ -1433,7 +1512,7 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
                   return(MagickFalse);
                 }
               pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
-              switch (compression)
+              switch (page_compression)
               {
                 default:
                 {
@@ -1461,13 +1540,13 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
       }
     else
       if ((image->storage_class == DirectClass) || (image->colors > 256) ||
-          (compression == JPEGCompression))
+          (page_compression == JPEGCompression))
         {
           /*
             Truecolor image.
           */
           (void) WriteBlobString(image,PS3_DirectClass"\n");
-          switch (compression)
+          switch (page_compression)
           {
             default:
             {
@@ -1498,7 +1577,7 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
           /*
             Image data.
           */
-          if (compression == JPEGCompression)
+          if (page_compression == JPEGCompression)
             status=InjectImageBlob(image_info,image,image,"jpeg",exception);
           else
             {
@@ -1513,7 +1592,7 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
                   return(MagickFalse);
                 }
               pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
-              switch (compression)
+              switch (page_compression)
               {
                 default:
                 {
@@ -1545,7 +1624,7 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
               Colormapped images.
             */
             (void) WriteBlobString(image,PS3_PseudoClass"\n");
-            switch (compression)
+            switch (page_compression)
             {
               default:
               {
@@ -1577,16 +1656,15 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
             /*
               Color map - uncompressed.
             */
-            if ((compression != NoCompression) &&
-                (compression != UndefinedCompression))
+            if (PS3IsBinary(page_compression) != MagickFalse)
               {
                 for (i=0; i < (ssize_t) image->colors; i++)
                 {
-                  pixel=ScaleQuantumToChar((Quantum) image->colormap[i].red);
+                  pixel=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red));
                   (void) WriteBlobByte(image,(unsigned char) pixel);
-                  pixel=ScaleQuantumToChar((Quantum) image->colormap[i].green);
+                  pixel=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));
                   (void) WriteBlobByte(image,(unsigned char) pixel);
-                  pixel=ScaleQuantumToChar((Quantum) image->colormap[i].blue);
+                  pixel=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue));
                   (void) WriteBlobByte(image,(unsigned char) pixel);
                 }
               }
@@ -1604,9 +1682,9 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
                 q=colormap;
                 for (i=0; i < (ssize_t) image->colors; i++)
                 {
-                  *q++=ScaleQuantumToChar((Quantum) image->colormap[i].red);
-                  *q++=ScaleQuantumToChar((Quantum) image->colormap[i].green);
-                  *q++=ScaleQuantumToChar((Quantum) image->colormap[i].blue);
+                  *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red));
+                  *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));
+                  *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue));
                 }
                 status=Ascii85EncodeImage(image,(size_t) (q-colormap),colormap,
                   exception);
@@ -1625,7 +1703,7 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
                 return(MagickFalse);
               }
             pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
-            switch (compression)
+            switch (page_compression)
             {
               default:
               {
@@ -1659,18 +1737,21 @@ static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image,
     /*
       Update BeginData now that we know the data size.
     */
-    length=(size_t) (TellBlob(image)-stop);
-    stop=TellBlob(image);
-    if (stop < 0)
+    end=TellBlob(image);
+    if (end < 0)
       ThrowWriterException(CorruptImageError,"ImproperImageHeader");
+    length=(size_t) (end-stop);
+    stop=end;
     offset=SeekBlob(image,start,SEEK_SET);
     if (offset < 0)
       ThrowWriterException(CorruptImageError,"ImproperImageHeader");
     (void) FormatLocaleString(buffer,MagickPathExtent,
       "%%%%BeginData:%13ld %s Bytes\n",(long) length,
-      compression == NoCompression ? "ASCII" : "BINARY");
+      PS3IsBinary(page_compression) != MagickFalse ? "BINARY" : "ASCII");
     (void) WriteBlobString(image,buffer);
     offset=SeekBlob(image,stop,SEEK_SET);
+    if (offset < 0)
+      ThrowWriterException(CorruptImageError,"ImproperImageHeader");
     (void) WriteBlobString(image,"%%EndData\n");
     /*
       End private dictionary if this an EPS.