Commit 094eedf56 for imagemagick.org

commit 094eedf567cd713d9d7eb9dd7a94fc0f255f492e
Author: Cristy <urban-warrior@imagemagick.org>
Date:   Thu Dec 3 20:03:36 2026 -0500

    a two-color image with a transparent key color now creates the color palette

diff --git a/coders/sixel.c b/coders/sixel.c
index 88a190f15..5433a5f46 100644
--- a/coders/sixel.c
+++ b/coders/sixel.c
@@ -81,6 +81,9 @@
 */
 #define SIXEL_PALETTE_MAX 1024
 #define SIXEL_OUTPUT_PACKET_SIZE 1024
+#define SIXEL_UNSET ((sixel_pixel_t) 0xffff) /* pixel never drawn */
+#define SIXEL_INITIAL_EXTENT 512
+#define SIXEL_MIN_EXTENT_LIMIT 4096

 /*
   Macros
@@ -201,7 +204,7 @@ static int hls_to_rgb(int hue, int lum, int sat)
   return(SIXEL_RGB(r,g,b));
 }

-static unsigned char *get_params(unsigned char *p, int *param, int *len)
+static unsigned char *get_params(unsigned char *p,int *param,int *len)
 {
   int
     n;
@@ -213,21 +216,20 @@ static unsigned char *get_params(unsigned char *p, int *param, int *len)
       p++;
     if (isdigit((int) ((unsigned char) *p)))
       {
-        for (n = 0; isdigit((int) ((unsigned char) *p)); p++)
+        for (n=0; isdigit((int) ((unsigned char) *p)); p++)
         {
-          int digit = *p-'0';
-          ssize_t tmp = (ssize_t) n*10+digit;
+          int
+            digit;

-          if (tmp > INT_MAX)
-            {
-              n=INT_MAX;
-              break;
-            }
-          n=(int) tmp;
+          digit=(int) (*p-'0');
+          if (n > ((INT_MAX-digit)/10))
+            n=INT_MAX;  /* saturate, but keep consuming the digits */
+          else
+            n=n*10+digit;
         }
         if (*len < 10)
           param[(*len)++]=n;
-        while (*p == ' ' || *p == '\t')
+        while ((*p == ' ') || (*p == '\t'))
           p++;
         if (*p == ';')
           p++;
@@ -241,7 +243,108 @@ static unsigned char *get_params(unsigned char *p, int *param, int *len)
     else
       break;
   }
-  return p;
+  return(p);
+}
+
+/*
+  Grow the working canvas so it is at least need_width x need_height.  When
+  exact is false each dimension doubles until it fits.  The old canvas is
+  always released on failure so the caller only has to return.
+*/
+static MagickBooleanType sixel_grow_canvas(Image *image,
+  sixel_pixel_t **canvas,ssize_t *width,ssize_t *height,
+  const ssize_t need_width,const ssize_t need_height,
+  const MagickBooleanType exact,ExceptionInfo *exception)
+{
+  MagickSizeType
+    guard,
+    limit_height,
+    limit_width;
+
+  size_t
+    extent;
+
+  sixel_pixel_t
+    *buffer;
+
+  ssize_t
+    i,
+    new_height,
+    new_width,
+    y;
+
+  /*
+    A tiny file must not be able to request an enormous canvas.  Run-length
+    encoding legitimately expands data, so allow a generous floor.
+  */
+  guard=(MagickSizeType) MagickMax(GetBlobSize(image),
+    (MagickSizeType) SIXEL_MIN_EXTENT_LIMIT);
+  if (((MagickSizeType) need_width > guard) ||
+      ((MagickSizeType) need_height > guard))
+    {
+      *canvas=(sixel_pixel_t *) RelinquishMagickMemory(*canvas);
+      (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
+        "InsufficientImageDataInFile","`%s'",image->filename);
+      return(MagickFalse);
+    }
+  limit_width=GetMagickResourceLimit(WidthResource);
+  limit_height=GetMagickResourceLimit(HeightResource);
+  new_width=(*width);
+  new_height=(*height);
+  if (need_width > new_width)
+    {
+      if (exact != MagickFalse)
+        new_width=need_width;
+      else
+        while (new_width < need_width)
+          new_width*=2;
+      if ((MagickSizeType) new_width > limit_width)
+        new_width=need_width;
+    }
+  if (need_height > new_height)
+    {
+      if (exact != MagickFalse)
+        new_height=need_height;
+      else
+        while (new_height < need_height)
+          new_height*=2;
+      if ((MagickSizeType) new_height > limit_height)
+        new_height=need_height;
+    }
+  if (((MagickSizeType) new_width > limit_width) ||
+      ((MagickSizeType) new_height > limit_height))
+    {
+      *canvas=(sixel_pixel_t *) RelinquishMagickMemory(*canvas);
+      (void) ThrowMagickException(exception,GetMagickModule(),ImageError,
+        "WidthOrHeightExceedsLimit","`%s'",image->filename);
+      return(MagickFalse);
+    }
+  if (HeapOverflowSanityCheckGetSize((size_t) new_width,(size_t) new_height,
+        &extent) != MagickFalse)
+    {
+      *canvas=(sixel_pixel_t *) RelinquishMagickMemory(*canvas);
+      (void) ThrowMagickException(exception,GetMagickModule(),
+        ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
+      return(MagickFalse);
+    }
+  buffer=(sixel_pixel_t *) AcquireQuantumMemory(extent,sizeof(*buffer));
+  if (buffer == (sixel_pixel_t *) NULL)
+    {
+      *canvas=(sixel_pixel_t *) RelinquishMagickMemory(*canvas);
+      (void) ThrowMagickException(exception,GetMagickModule(),
+        ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
+      return(MagickFalse);
+    }
+  for (i=0; i < (ssize_t) extent; i++)
+    buffer[i]=SIXEL_UNSET;
+  for (y=0; y < (*height); y++)
+    (void) memcpy(buffer+new_width*y,(*canvas)+(*width)*y,(size_t) (*width)*
+      sizeof(*buffer));
+  *canvas=(sixel_pixel_t *) RelinquishMagickMemory(*canvas);
+  *canvas=buffer;
+  *width=new_width;
+  *height=new_height;
+  return(MagickTrue);
 }

 /* convert sixel data into indexed pixel bytes and palette data */
@@ -250,226 +353,124 @@ static MagickBooleanType sixel_decode(Image *image,unsigned char *p,
   unsigned char **palette,size_t *ncolors,ExceptionInfo *exception)
 {
   int
-    attributed_pad,
-    attributed_pan,
-    attributed_ph,
-    attributed_pv,
     b,
-    background_color_index,
     c,
     color_index,
     g,
-    n,
     max_color_index,
-    max_x,
-    max_y,
+    n,
     param[10],
-    position_x,
-    position_y,
     r,
     repeat_count,
     sixel_palet[SIXEL_PALETTE_MAX],
-    sixel_vertical_mask,
-    transparent_index; /* NEW: track transparent palette index */
+    sixel_vertical_mask;

-  sixel_pixel_t
-    *dmbuf,
-    *imbuf;
+  MagickBooleanType
+    has_transparent,
+    transparent_background;

   size_t
     extent;

+  sixel_pixel_t
+    *dmbuf,
+    *imbuf;
+
   ssize_t
+    attributed_ph,
+    attributed_pv,
     dmsx,
     dmsy,
     i,
     imsx,
     imsy,
+    max_x,
+    max_y,
     offset,
+    position_x,
+    position_y,
+    transparent_index,
     x,
     y;

-  extent=strlen((char *) p);
   position_x=position_y=0;
   max_x=max_y=0;
-  attributed_pan=2;
-  attributed_pad=1;
   attributed_ph=attributed_pv=0;
   repeat_count=1;
   color_index=0;
-  background_color_index=0;
   max_color_index=2;
-  transparent_index=-1; /* NEW: initialize as "no transparency" */
+  transparent_background=MagickFalse;
+  has_transparent=MagickFalse;
   memset(param,0,sizeof(param));
-  imsx=2048;
-  imsy=2048;
-  if (((MagickSizeType) imsx > GetBlobSize(image)) ||
-      ((MagickSizeType) imsy > GetBlobSize(image)))
+  imsx=SIXEL_INITIAL_EXTENT;
+  imsy=SIXEL_INITIAL_EXTENT;
+  imbuf=(sixel_pixel_t *) AcquireQuantumMemory((size_t) imsx,(size_t) imsy*
+    sizeof(*imbuf));
+  if (imbuf == (sixel_pixel_t *) NULL)
     {
-      (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
-        "InsufficientImageDataInFile","`%s'",image->filename);
+      (void) ThrowMagickException(exception,GetMagickModule(),
+        ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
       return(MagickFalse);
     }
-  if (SetImageExtent(image,(size_t) imsx,(size_t) imsy,exception) == MagickFalse)
-    return(MagickFalse);
-  imbuf=(sixel_pixel_t *) AcquireQuantumMemory((size_t) imsx,
-    (size_t) imsy*sizeof(sixel_pixel_t));
-  if (imbuf == (sixel_pixel_t *) NULL)
-    return(MagickFalse);
-  for (n = 0; n < 16; n++)
+  for (i=0; i < (imsx*imsy); i++)
+    imbuf[i]=SIXEL_UNSET;
+  for (n=0; n < 16; n++)
     sixel_palet[n]=sixel_default_color_table[n];
   /* colors 16-231 are a 6x6x6 color cube */
   for (r=0; r < 6; r++)
-  {
     for (g=0; g < 6; g++)
-    {
       for (b=0; b < 6; b++)
-      {
         sixel_palet[n++]=SIXEL_RGB(r*51,g*51,b*51);
-      }
-    }
-  }
-  /* colors 232-255 are a grayscale ramp, intentionally leaving out */
+  /* colors 232-255 are a grayscale ramp */
   for (i=0; i < 24; i++)
     sixel_palet[n++]=SIXEL_RGB(i*11,i*11,i*11);
   for (; n < SIXEL_PALETTE_MAX; n++)
     sixel_palet[n]=SIXEL_RGB(255,255,255);
-  for (i = 0; i < (imsx*imsy); i++)
-    imbuf[i]=(sixel_pixel_t) background_color_index;
   while (*p != '\0')
   {
-    if ((p[0] == '\033' && p[1] == 'P') || (*p == 0x90))
+    if (((p[0] == '\033') && (p[1] == 'P')) || (*p == 0x90))
       {
+        /* DCS P1 ; P2 ; P3 q -- P2 == 1 means undrawn pixels are transparent */
         if (*p == '\033')
           p++;
-        p=get_params(++p,param,&n);
+        p=get_params(p+1,param,&n);
         if (*p == 'q')
           {
             p++;
-            if (n > 0)
-              {
-                /* Pn1 */
-                switch(param[0])
-                {
-                  case 0:
-                  case 1:
-                    attributed_pad = 2;
-                    break;
-                  case 2:
-                    attributed_pad = 5;
-                    break;
-                  case 3:
-                    attributed_pad = 4;
-                    break;
-                  case 4:
-                    attributed_pad = 4;
-                    break;
-                  case 5:
-                    attributed_pad = 3;
-                    break;
-                  case 6:
-                    attributed_pad = 3;
-                    break;
-                  case 7:
-                    attributed_pad = 2;
-                    break;
-                  case 8:
-                    attributed_pad = 2;
-                    break;
-                  case 9:
-                    attributed_pad = 1;
-                    break;
-                }
-              }
-            if (n > 2)
-              {
-                /* Pn3 */
-                if (param[2] == 0)
-                  param[2]=10;
-                attributed_pan=(int) (((ssize_t) attributed_pan*param[2])/10);
-                attributed_pad=(int) (((ssize_t) attributed_pad*param[2])/10);
-                if (attributed_pan <= 0)
-                  attributed_pan=1;
-                if (attributed_pad <= 0)
-                  attributed_pad=1;
-              }
+            transparent_background=((n > 1) && (param[1] == 1)) ? MagickTrue :
+              MagickFalse;
           }
       }
-    else if ((p[0] == '\033' && p[1] == '\\') || (*p == 0x9C))
+    else if (((p[0] == '\033') && (p[1] == '\\')) || (*p == 0x9C))
       break;
     else if (*p == '"')
       {
         /* DECGRA Set Raster Attributes " Pan; Pad; Ph; Pv */
-        p=get_params(++p,param,&n);
-        if (n > 0)
-          attributed_pad=param[0];
-        if (n > 1)
-          attributed_pan=param[1];
+        p=get_params(p+1,param,&n);
         if ((n > 2) && (param[2] > 0))
-          attributed_ph=param[2]&0xffff;
+          attributed_ph=(ssize_t) (param[2] & 0xffff);
         if ((n > 3) && (param[3] > 0))
-          attributed_pv=param[3]&0xffff;
-        if (attributed_pan <= 0)
-          attributed_pan=1;
-        if (attributed_pad <= 0)
-          attributed_pad=1;
+          attributed_pv=(ssize_t) (param[3] & 0xffff);
         if ((imsx < attributed_ph) || (imsy < attributed_pv))
-          {
-            dmsx=imsx > attributed_ph ? imsx : attributed_ph;
-            dmsy=imsy > attributed_pv ? imsy : attributed_pv;
-            if (((MagickSizeType) dmsx > GetBlobSize(image)) ||
-                ((MagickSizeType) dmsy > GetBlobSize(image)))
-              {
-                imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
-                (void) ThrowMagickException(exception,GetMagickModule(),
-                  CorruptImageError,"InsufficientImageDataInFile","`%s'",
-                  image->filename);
-                return(MagickFalse);
-              }
-            if (SetImageExtent(image,(size_t) dmsx,(size_t) dmsy,exception) == MagickFalse)
-              {
-                imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
-                return(MagickFalse);
-              }
-            dmbuf=(sixel_pixel_t *) AcquireQuantumMemory((size_t) dmsx,(size_t)
-              dmsy*sizeof(sixel_pixel_t));
-            if (dmbuf == (sixel_pixel_t *) NULL)
-              {
-                imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
-                return(MagickFalse);
-              }
-            (void) memset(dmbuf,background_color_index,(size_t) dmsx*(size_t)
-              dmsy*sizeof(sixel_pixel_t));
-            for (y=0; y < imsy; ++y)
-              (void) memcpy(dmbuf+dmsx*y,imbuf+imsx*y,(size_t) imsx*
-                sizeof(sixel_pixel_t));
-            imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
-            imsx=dmsx;
-            imsy=dmsy;
-            imbuf=dmbuf;
-          }
+          if (sixel_grow_canvas(image,&imbuf,&imsx,&imsy,attributed_ph,
+                attributed_pv,MagickTrue,exception) == MagickFalse)
+            return(MagickFalse);
       }
     else if (*p == '!')
       {
         /* DECGRI Graphics Repeat Introducer ! Pn Ch */
-        p=get_params(++p,param,&n);
+        p=get_params(p+1,param,&n);
         if ((n > 0) && (param[0] > 0))
-          {
-            repeat_count=param[0];
-            if (repeat_count > (ssize_t) extent)
-              break;
-          }
+          repeat_count=param[0];
       }
     else if (*p == '#')
       {
         /* DECGCI Graphics Color Introducer # Pc; Pu; Px; Py; Pz */
-        p=get_params(++p,param,&n);
-
+        p=get_params(p+1,param,&n);
         if (n > 0)
           {
-            if ((color_index = param[0]) < 0)
-              color_index=0;
-            else if (color_index >= SIXEL_PALETTE_MAX)
+            color_index=param[0];
+            if (color_index >= SIXEL_PALETTE_MAX)
               color_index=SIXEL_PALETTE_MAX-1;
           }
         if (n > 4)
@@ -488,30 +489,15 @@ static MagickBooleanType sixel_decode(Image *image,unsigned char *p,
               }
             else if (param[1] == 2)
               {
-                /*
-                  RGB or transparency.
-
-                  libsixel-style transparency is encoded as:
-                    #N;2;0;0;0
-                  Treat this as "palette index N is fully transparent".
-                */
-                if (param[2] == 0 && param[3] == 0 && param[4] == 0)
-                  {
-                    transparent_index=color_index;
-                    /* leave sixel_palet[color_index] as-is; alpha will be 0 */
-                  }
-                else
-                  {
-                    /* RGB */
-                    if (param[2] > 100)
-                      param[2]=100;
-                    if (param[3] > 100)
-                      param[3]=100;
-                    if (param[4] > 100)
-                      param[4]=100;
-                    sixel_palet[color_index]=SIXEL_XRGB(param[2],param[3],
-                      param[4]);
-                  }
+                /* RGB, each component in percent */
+                if (param[2] > 100)
+                  param[2]=100;
+                if (param[3] > 100)
+                  param[3]=100;
+                if (param[4] > 100)
+                  param[4]=100;
+                sixel_palet[color_index]=SIXEL_XRGB(param[2],param[3],
+                  param[4]);
               }
           }
       }
@@ -532,70 +518,25 @@ static MagickBooleanType sixel_decode(Image *image,unsigned char *p,
       }
     else if ((*p >= '?') && (*p <= '\177'))
       {
-        if ((imsx < ((ssize_t) position_x+repeat_count)) ||
-            (imsy < ((ssize_t) position_y+6)))
-          {
-            ssize_t
-              nx,
-              ny;
-
-            nx=imsx*2;
-            ny=imsy*2;
-
-            while ((nx < ((ssize_t) position_x+repeat_count)) || (ny < ((ssize_t) position_y+6)))
-            {
-              nx *= 2;
-              ny *= 2;
-            }
-
-            dmsx=nx;
-            dmsy=ny;
-            if (((MagickSizeType) dmsx > GetBlobSize(image)) ||
-                ((MagickSizeType) dmsy > GetBlobSize(image)))
-              {
-                imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
-                (void) ThrowMagickException(exception,GetMagickModule(),
-                  CorruptImageError,"InsufficientImageDataInFile","`%s'",
-                  image->filename);
-                return(MagickFalse);
-              }
-            if (SetImageExtent(image,(size_t) dmsx,(size_t) dmsy,exception) == MagickFalse)
-              {
-                imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
-                return(MagickFalse);
-              }
-            dmbuf=(sixel_pixel_t *) AcquireQuantumMemory((size_t) dmsx,(size_t)
-              dmsy*sizeof(sixel_pixel_t));
-            if (dmbuf == (sixel_pixel_t *) NULL)
-              {
-                imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
-                return(MagickFalse);
-              }
-            (void) memset(dmbuf,background_color_index,(size_t) dmsx*(size_t)
-              dmsy*sizeof(sixel_pixel_t));
-            for (y = 0; y < imsy; ++y)
-              (void) memcpy(dmbuf+dmsx*y,imbuf+imsx*y,(size_t) imsx*
-                sizeof(sixel_pixel_t));
-            imbuf = (sixel_pixel_t *) RelinquishMagickMemory(imbuf);
-            imsx=dmsx;
-            imsy=dmsy;
-            imbuf=dmbuf;
-          }
+        if ((imsx < (position_x+repeat_count)) || (imsy < (position_y+6)))
+          if (sixel_grow_canvas(image,&imbuf,&imsx,&imsy,
+                position_x+repeat_count,position_y+6,MagickFalse,
+                exception) == MagickFalse)
+            return(MagickFalse);
         if (color_index > max_color_index)
-          max_color_index = color_index;
-        if ((b = *(p++) - '?') == 0)
-          position_x += repeat_count;
+          max_color_index=color_index;
+        if ((b=*(p++)-'?') == 0)
+          position_x+=repeat_count;
         else
           {
             sixel_vertical_mask=0x01;
             if (repeat_count <= 1)
               {
-                for (i = 0; i < 6; i++)
+                for (i=0; i < 6; i++)
                 {
                   if ((b & sixel_vertical_mask) != 0)
                     {
-                      offset=(ssize_t) (imsx*((ssize_t) position_y+i)+
-                        (ssize_t) position_x);
+                      offset=imsx*(position_y+i)+position_x;
                       if ((offset < 0) || (offset >= (imsx*imsy)))
                         {
                           imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
@@ -603,17 +544,17 @@ static MagickBooleanType sixel_decode(Image *image,unsigned char *p,
                         }
                       imbuf[offset]=(sixel_pixel_t) color_index;
                       if (max_x < position_x)
-                          max_x = position_x;
-                      if (max_y < (position_y + i))
-                          max_y = (int) (position_y + i);
+                        max_x=position_x;
+                      if (max_y < (position_y+i))
+                        max_y=position_y+i;
                     }
                   sixel_vertical_mask <<= 1;
                 }
-                position_x += 1;
+                position_x++;
               }
             else  /* repeat_count > 1 */
               {
-                for (i = 0; i < 6; i++)
+                for (i=0; i < 6; i++)
                 {
                   if ((b & sixel_vertical_mask) != 0)
                     {
@@ -624,88 +565,110 @@ static MagickBooleanType sixel_decode(Image *image,unsigned char *p,
                           break;
                         c <<= 1;
                       }
-                      for (y = position_y + i; y < position_y + i + n; ++y)
+                      for (y=position_y+i; y < (position_y+i+n); ++y)
                       {
-                        offset=(imsx*y+position_x);
-                        if ((offset < 0) || ((offset+repeat_count) >= (imsx*imsy)))
+                        offset=imsx*y+position_x;
+                        if ((offset < 0) || ((offset+repeat_count) > (imsx*imsy)))
                           {
                             imbuf=(sixel_pixel_t *)
                               RelinquishMagickMemory(imbuf);
                             return(MagickFalse);
                           }
-                        for (x = 0; x < repeat_count; x++)
-                          imbuf[(size_t) offset+x]=(sixel_pixel_t) color_index;
+                        for (x=0; x < repeat_count; x++)
+                          imbuf[offset+x]=(sixel_pixel_t) color_index;
                       }
                       if (max_x < (position_x+repeat_count-1))
-                        max_x = position_x+repeat_count-1;
+                        max_x=position_x+repeat_count-1;
                       if (max_y < (position_y+i+n-1))
-                        max_y = (int) (position_y+i+n-1);
+                        max_y=position_y+i+n-1;
                       i+=(n-1);
                       sixel_vertical_mask <<= (n-1);
                     }
                   sixel_vertical_mask <<= 1;
                 }
-                position_x += repeat_count;
+                position_x+=repeat_count;
               }
           }
-          repeat_count = 1;
+        repeat_count=1;
       }
     else
       p++;
   }
   if (++max_x < attributed_ph)
-    max_x = attributed_ph;
+    max_x=attributed_ph;
   if (++max_y < attributed_pv)
-    max_y = attributed_pv;
+    max_y=attributed_pv;
   if ((imsx > max_x) || (imsy > max_y))
     {
+      /*
+        Crop the canvas to the extent of the image.
+      */
       dmsx=max_x;
       dmsy=max_y;
-      if (((MagickSizeType) dmsx > GetBlobSize(image)) ||
-          ((MagickSizeType) dmsy > GetBlobSize(image)))
+      if (HeapOverflowSanityCheckGetSize((size_t) dmsx,(size_t) dmsy,
+            &extent) != MagickFalse)
         {
           imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
           (void) ThrowMagickException(exception,GetMagickModule(),
-            CorruptImageError,"InsufficientImageDataInFile","`%s'",
-            image->filename);
+            ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
           return(MagickFalse);
         }
-      if (SetImageExtent(image,(size_t) dmsx,(size_t) dmsy,exception) == MagickFalse)
-        {
-          imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
-          return(MagickFalse);
-        }
-      dmbuf=(sixel_pixel_t *) AcquireQuantumMemory((size_t) dmsx,(size_t) dmsy*
-        sizeof(sixel_pixel_t));
+      dmbuf=(sixel_pixel_t *) AcquireQuantumMemory(extent,sizeof(*dmbuf));
       if (dmbuf == (sixel_pixel_t *) NULL)
         {
           imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
+          (void) ThrowMagickException(exception,GetMagickModule(),
+            ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
           return(MagickFalse);
         }
       for (y=0; y < dmsy; ++y)
-        (void) memcpy(dmbuf+dmsx*y,imbuf+imsx*y,(size_t) dmsx*
-          sizeof(sixel_pixel_t));
+        (void) memcpy(dmbuf+dmsx*y,imbuf+imsx*y,(size_t) dmsx*sizeof(*dmbuf));
       imbuf=(sixel_pixel_t *) RelinquishMagickMemory(imbuf);
       imsx=dmsx;
       imsy=dmsy;
       imbuf=dmbuf;
     }
-
+  /*
+    Resolve pixels that were never drawn.  With P2 == 1 they are transparent
+    and get an extra palette entry; otherwise they take the background color.
+  */
+  transparent_index=(ssize_t) max_color_index+1;
+  for (i=0; i < (imsx*imsy); i++)
+    if (imbuf[i] == SIXEL_UNSET)
+      {
+        if (transparent_background != MagickFalse)
+          {
+            imbuf[i]=(sixel_pixel_t) transparent_index;
+            has_transparent=MagickTrue;
+          }
+        else
+          imbuf[i]=0;
+      }
   *pixels=imbuf;
   *pwidth=(size_t) imsx;
   *pheight=(size_t) imsy;
-  *ncolors=(size_t) max_color_index+1;
+  *ncolors=(size_t) max_color_index+1+(has_transparent != MagickFalse ? 1 : 0);
   *palette=(unsigned char *) AcquireQuantumMemory(*ncolors,4);
   if (*palette == (unsigned char *) NULL)
-    return(MagickFalse);
-  for (n = 0; n < (ssize_t) *ncolors; ++n)
+    {
+      (void) ThrowMagickException(exception,GetMagickModule(),
+        ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
+      return(MagickFalse);
+    }
+  for (i=0; i < (ssize_t) *ncolors; ++i)
   {
-    (*palette)[n*4+0]=sixel_palet[n] >> 16 & 0xff;
-    (*palette)[n*4+1]=sixel_palet[n] >> 8 & 0xff;
-    (*palette)[n*4+2]=sixel_palet[n] & 0xff;
-    (*palette)[n*4+3]=0xff; /* default: opaque */
-    if (n == transparent_index)
-      (*palette)[n*4+3]=0x00; /* NEW: transparent entry */
+    if ((has_transparent != MagickFalse) && (i == transparent_index))
+      {
+        (*palette)[i*4+0]=0;
+        (*palette)[i*4+1]=0;
+        (*palette)[i*4+2]=0;
+        (*palette)[i*4+3]=0x00;  /* transparent entry */
+        continue;
+      }
+    (*palette)[i*4+0]=(unsigned char) ((sixel_palet[i] >> 16) & 0xff);
+    (*palette)[i*4+1]=(unsigned char) ((sixel_palet[i] >> 8) & 0xff);
+    (*palette)[i*4+2]=(unsigned char) (sixel_palet[i] & 0xff);
+    (*palette)[i*4+3]=0xff;
   }
   return(MagickTrue);
 }
@@ -755,8 +718,8 @@ static int sixel_put_flash(sixel_output_t *const context)
     {
       /* DECGRI Graphics Repeat Introducer ! Pn Ch */
       nwrite=(int) FormatLocaleString((char *) context->buffer+context->pos,
-        sizeof(context->buffer),"!%d%c",context->save_count,
-        (char) context->save_pixel);
+        sizeof(context->buffer)-(size_t) context->pos,"!%d%c",
+        context->save_count,(char) context->save_pixel);
       if (sixel_advance(context,nwrite) == MagickFalse)
         return(-1);
     }
@@ -814,23 +777,20 @@ static void sixel_node_del(sixel_output_t *const context,sixel_node_t *np)
   context->node_free=np;
 }

-static int sixel_put_node(sixel_output_t *const context,int x,sixel_node_t *np,
-  int ncolors,int keycolor)
+static int sixel_put_node(sixel_output_t *const context,int x,
+  sixel_node_t *np)
 {
   int
     nwrite;

-  if ((ncolors != 2) || (keycolor == -1))
+  /* designate palette index */
+  if (context->active_palette != np->color)
     {
-      /* designate palette index */
-      if (context->active_palette != np->color)
-        {
-          nwrite=(int) FormatLocaleString((char *) context->buffer+
-            context->pos,sizeof(context->buffer),"#%d",np->color);
-          if (sixel_advance(context,nwrite) == MagickFalse)
-            return(-1);
-          context->active_palette=np->color;
-        }
+      nwrite=(int) FormatLocaleString((char *) context->buffer+context->pos,
+        sizeof(context->buffer)-(size_t) context->pos,"#%d",np->color);
+      if (sixel_advance(context,nwrite) == MagickFalse)
+        return(-1);
+      context->active_palette=np->color;
     }
   for (; x < np->left; x++)
     if (sixel_put_pixel(context,0) == MagickFalse)
@@ -892,37 +852,39 @@ static MagickBooleanType sixel_encode_impl(sixel_pixel_t *pixels,size_t width,
   if (map == (sixel_pixel_t *) NULL)
     return (MagickFalse);
   (void) memset(map,0,len*sizeof(sixel_pixel_t));
-  if (context->has_8bit_control)
-    nwrite=(int) FormatLocaleString((char *) context->buffer,sizeof(context->buffer),
-      "\x90" "0;1;0" "q");
-  else
-    nwrite=(int) FormatLocaleString((char *) context->buffer,sizeof(context->buffer),
-      "\x1bP" "0;1;0" "q");
+  /*
+    DCS P1;P2;P3 q: P2 == 1 leaves undrawn pixels transparent, which is what
+    a keycolor needs; otherwise use P2 == 0 (background is filled).
+  */
+  nwrite=(int) FormatLocaleString((char *) context->buffer,
+    sizeof(context->buffer),"%s0;%d;0q",context->has_8bit_control != 0 ?
+    "\x90" : "\x1bP",keycolor >= 0 ? 1 : 0);
   if (sixel_advance(context,nwrite) == MagickFalse)
     {
       RelinquishNodesAndMap;
       return(MagickFalse);
     }
   nwrite=(int) FormatLocaleString((char *) context->buffer+context->pos,
-    sizeof(context->buffer),"\"1;1;%d;%d",(int) width,(int) height);
+    sizeof(context->buffer)-(size_t) context->pos,"\"1;1;%d;%d",(int) width,
+    (int) height);
   if (sixel_advance(context,nwrite) == MagickFalse)
     {
       RelinquishNodesAndMap;
       return(MagickFalse);
     }
-  if ((ncolors != 2) || (keycolor == -1))
-    for (n = 0; n < (ssize_t) ncolors; n++)
-    {
-        /* DECGCI Graphics Color Introducer  # Pc ; Pu; Px; Py; Pz */
-        nwrite=(int) FormatLocaleString((char *) context->buffer+context->pos,
-          sizeof(context->buffer),"#%d;2;%d;%d;%d",n,(palette[n*3+0]*100+127)/
-          255,(palette[n*3+1]*100+127)/255,(palette[n*3+2]*100+127)/255);
-        if (sixel_advance(context,nwrite) == MagickFalse)
-          {
-            RelinquishNodesAndMap;
-            return(MagickFalse);
-          }
-    }
+  for (n=0; n < (int) ncolors; n++)
+  {
+    /* DECGCI Graphics Color Introducer  # Pc ; Pu; Px; Py; Pz */
+    nwrite=(int) FormatLocaleString((char *) context->buffer+context->pos,
+      sizeof(context->buffer)-(size_t) context->pos,"#%d;2;%d;%d;%d",n,
+      (palette[n*3+0]*100+127)/255,(palette[n*3+1]*100+127)/255,
+      (palette[n*3+2]*100+127)/255);
+    if (sixel_advance(context,nwrite) == MagickFalse)
+      {
+        RelinquishNodesAndMap;
+        return(MagickFalse);
+      }
+  }
   for (y=i=0; y < (int) height; y++)
   {
     for (x=0; x < (int) width; x++)
@@ -995,7 +957,7 @@ static MagickBooleanType sixel_encode_impl(sixel_pixel_t *pixels,size_t width,
             }
           x=0;
         }
-      x=sixel_put_node(context,x,np,(int) ncolors,keycolor);
+      x=sixel_put_node(context,x,np);
       if (x < 0)
         {
           RelinquishNodesAndMap;
@@ -1010,7 +972,7 @@ static MagickBooleanType sixel_encode_impl(sixel_pixel_t *pixels,size_t width,
             np=np->next;
             continue;
           }
-          x=sixel_put_node(context,x,np,(int) ncolors,keycolor);
+          x=sixel_put_node(context,x,np);
           if (x < 0)
             {
               RelinquishNodesAndMap;
@@ -1115,7 +1077,7 @@ static MagickBooleanType IsSIXEL(const unsigned char *magick,
 %                                                                             %
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %
-%  ReadSIXELImage() reads an X11 pixmap image file and returns it.  It
+%  ReadSIXELImage() reads a DEC SIXEL image file and returns it.  It
 %  allocates the memory necessary for the new Image structure and returns a
 %  pointer to the new image.
 %
@@ -1142,28 +1104,36 @@ static Image *ReadSIXELImage(const ImageInfo *image_info,
     status;

   size_t
+    capacity,
     height,
     length,
     ncolors,
     width;

   sixel_pixel_t
-    *pixels = NULL;
+    *pixels = (sixel_pixel_t *) NULL;

   ssize_t
+    count,
     i,
     x,
     y;

   unsigned char
-    *p,
-    *palette = NULL,
-    *sixel_data = NULL;
+    *palette = (unsigned char *) NULL,
+    *sixel_data = (unsigned char *) NULL;

   /*
     Allocate image structure.
   */
-  image = AcquireImage(image_info,exception);
+  assert(image_info != (const ImageInfo *) NULL);
+  assert(image_info->signature == MagickCoreSignature);
+  assert(exception != (ExceptionInfo *) NULL);
+  assert(exception->signature == MagickCoreSignature);
+  if (IsEventLogging() != MagickFalse)
+    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
+      image_info->filename);
+  image=AcquireImage(image_info,exception);
   if (image == (Image *) NULL)
     return((Image *) NULL);
   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
@@ -1173,36 +1143,40 @@ static Image *ReadSIXELImage(const ImageInfo *image_info,
       return((Image *) NULL);
     }
   /*
-    Read SIXEL file.
+    Read the whole SIXEL stream.  Lines are not interpreted: '#' starts a
+    color definition in SIXEL and must never be treated as a comment.
   */
-  length=MagickPathExtent;
-  sixel_data=(unsigned char *) AcquireQuantumMemory((size_t) length+
-    MagickPathExtent,sizeof(*sixel_data));
-  p=sixel_data;
-  if (sixel_data != (unsigned char *) NULL)
-    while (ReadBlobString(image,(char *) p) != (char *) NULL)
-    {
-      ssize_t
-       offset;
-
-      if ((*p == '#') && ((p == sixel_data) || (*(p-1) == '\n')))
-        continue;
-      if ((*p == '}') && (*(p+1) == ';'))
-        break;
-      p+=(ptrdiff_t) strlen((char *) p);
-      offset=p-sixel_data;
-      if ((size_t) (offset+MagickPathExtent+1) < length)
-        continue;
-      length<<=1;
-      sixel_data=(unsigned char *) ResizeQuantumMemory(sixel_data,length+
-        MagickPathExtent+1,sizeof(*sixel_data));
-      if (sixel_data == (unsigned char *) NULL)
-        break;
-      p=sixel_data+offset;
-    }
+  capacity=MagickPathExtent;
+  length=0;
+  sixel_data=(unsigned char *) AcquireQuantumMemory(capacity+1,
+    sizeof(*sixel_data));
   if (sixel_data == (unsigned char *) NULL)
     ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+  for ( ; ; )
+  {
+    count=ReadBlob(image,capacity-length,sixel_data+length);
+    if (count <= 0)
+      break;
+    length+=(size_t) count;
+    if (length < capacity)
+      continue;
+    if (capacity > (((size_t) MAGICK_SSIZE_MAX)/2)-1)
+      {
+        sixel_data=(unsigned char *) RelinquishMagickMemory(sixel_data);
+        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+      }
+    capacity<<=1;
+    sixel_data=(unsigned char *) ResizeQuantumMemory(sixel_data,capacity+1,
+      sizeof(*sixel_data));
+    if (sixel_data == (unsigned char *) NULL)
+      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
+  }
   sixel_data[length]='\0';
+  if (length == 0)
+    {
+      sixel_data=(unsigned char *) RelinquishMagickMemory(sixel_data);
+      ThrowReaderException(CorruptImageError,"ImproperImageHeader");
+    }
   /*
     Decode SIXEL into:
       - pixels[] (indexed)
@@ -1212,87 +1186,87 @@ static Image *ReadSIXELImage(const ImageInfo *image_info,
   */
   status=sixel_decode(image,sixel_data,&pixels,&width,&height,&palette,
     &ncolors,exception);
+  sixel_data=(unsigned char *) RelinquishMagickMemory(sixel_data);
   if (status == MagickFalse)
     goto cleanup;
   /*
     Prepare image geometry.
   */
-  if ((width > GetBlobSize(image)) || (height > GetBlobSize(image)))
-    {
-      (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
-        "InsufficientImageDataInFile","`%s'",image->filename);
-      goto cleanup;
-    }
-  if (SetImageExtent(image,width,height,exception) == MagickFalse)
+  status=SetImageExtent(image,width,height,exception);
+  if (status == MagickFalse)
     goto cleanup;
   /*
     Allocate colormap.
   */
-  image->colors = ncolors;
-  if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
+  status=AcquireImageColormap(image,ncolors,exception);
+  if (status == MagickFalse)
     goto cleanup;
   /*
     Load palette into image->colormap and detect transparency.
   */
-  for (i = 0; i < (ssize_t) image->colors; i++)
+  for (i=0; i < (ssize_t) image->colors; i++)
   {
-    unsigned char r = palette[i*4+0];
-    unsigned char g = palette[i*4+1];
-    unsigned char b = palette[i*4+2];
-    unsigned char a = palette[i*4+3];
-
-    image->colormap[i].red   = ScaleCharToQuantum(r);
-    image->colormap[i].green = ScaleCharToQuantum(g);
-    image->colormap[i].blue  = ScaleCharToQuantum(b);
-    /* alpha stored as Quantum in ImageMagick */
-    image->colormap[i].alpha = (double) ScaleCharToQuantum(a);
-    if (a != 0xff)
-      has_alpha = MagickTrue;
+    image->colormap[i].red=(double) ScaleCharToQuantum(palette[i*4+0]);
+    image->colormap[i].green=(double) ScaleCharToQuantum(palette[i*4+1]);
+    image->colormap[i].blue=(double) ScaleCharToQuantum(palette[i*4+2]);
+    image->colormap[i].alpha=(double) ScaleCharToQuantum(palette[i*4+3]);
+    if (palette[i*4+3] != 0xff)
+      has_alpha=MagickTrue;
   }
   if (has_alpha != MagickFalse)
-    {
-      /*
-        If any palette entry is transparent, enable alpha channel.
-      */
-      image->alpha_trait = BlendPixelTrait;
-      (void) SetImageAlphaChannel(image,OnAlphaChannel,exception);
-    }
+    image->alpha_trait=BlendPixelTrait;
   /*
     Transfer indexed pixels into the image.
   */
-  for (y = 0; y < (ssize_t) image->rows; y++)
+  for (y=0; y < (ssize_t) image->rows; y++)
   {
-    Quantum *q = GetAuthenticPixels(image,0,y,image->columns,1,exception);
+    Quantum
+      *q;
+
+    q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
     if (q == (Quantum *) NULL)
-      break;
-    for (x = 0; x < (ssize_t) image->columns; x++)
+      {
+        status=MagickFalse;
+        break;
+      }
+    for (x=0; x < (ssize_t) image->columns; x++)
     {
-      Quantum index = (Quantum) pixels[y*(ssize_t) image->columns + x];
-      SetPixelIndex(image,index,q);
+      size_t
+        index;
+
+      index=(size_t) pixels[y*(ssize_t) image->columns+x];
+      if (index >= image->colors)
+        index=0;
+      SetPixelIndex(image,(Quantum) index,q);
       SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
-      if (has_alpha != MagickFalse)
-        {
-          /*
-            If this palette entry is transparent, set pixel alpha=0.
-          */
-          Quantum alpha_q = (Quantum) image->colormap[(int) index].alpha;
-          SetPixelAlpha(image,alpha_q,q);
-        }
       q+=GetPixelChannels(image);
     }
     if (SyncAuthenticPixels(image,exception) == MagickFalse)
-      break;
+      {
+        status=MagickFalse;
+        break;
+      }
   }

 cleanup:
-  if (pixels != NULL)
-    pixels = (sixel_pixel_t *) RelinquishMagickMemory(pixels);
-  if (palette != NULL)
-    palette = (unsigned char *) RelinquishMagickMemory(palette);
-  if (sixel_data != NULL)
-    sixel_data = (unsigned char *) RelinquishMagickMemory(sixel_data);
-
-  return(image);
+  if (pixels != (sixel_pixel_t *) NULL)
+    pixels=(sixel_pixel_t *) RelinquishMagickMemory(pixels);
+  if (palette != (unsigned char *) NULL)
+    palette=(unsigned char *) RelinquishMagickMemory(palette);
+  if (status == MagickFalse)
+    {
+      (void) CloseBlob(image);
+      image=DestroyImageList(image);
+      return((Image *) NULL);
+    }
+  if (CloseBlob(image) == MagickFalse)
+    status=MagickFalse;
+  if (status == MagickFalse)
+    {
+      image=DestroyImageList(image);
+      return((Image *) NULL);
+    }
+  return(GetFirstImageInList(image));
 }

 /*
@@ -1327,13 +1301,13 @@ ModuleExport size_t RegisterSIXELImage(void)
   entry->decoder=(DecodeImageHandler *) ReadSIXELImage;
   entry->encoder=(EncodeImageHandler *) WriteSIXELImage;
   entry->magick=(IsImageFormatHandler *) IsSIXEL;
-  entry->flags^=CoderAdjoinFlag;
+  entry->flags&=~CoderAdjoinFlag;
   (void) RegisterMagickInfo(entry);
   entry=AcquireMagickInfo("SIXEL","SIX","DEC SIXEL Graphics Format");
   entry->decoder=(DecodeImageHandler *) ReadSIXELImage;
   entry->encoder=(EncodeImageHandler *) WriteSIXELImage;
   entry->magick=(IsImageFormatHandler *) IsSIXEL;
-  entry->flags^=CoderAdjoinFlag;
+  entry->flags&=~CoderAdjoinFlag;
   (void) RegisterMagickInfo(entry);
   return(MagickImageCoderSignature);
 }
@@ -1374,7 +1348,7 @@ ModuleExport void UnregisterSIXELImage(void)
 %                                                                             %
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %
-%  WriteSIXELImage() writes an image to a file in the X pixmap format.
+%  WriteSIXELImage() writes an image to a file in the DEC SIXEL format.
 %
 %  The format of the WriteSIXELImage method is:
 %
@@ -1421,11 +1395,18 @@ static MagickBooleanType WriteSIXELImage(const ImageInfo *image_info,
   assert(image_info->signature == MagickCoreSignature);
   assert(image != (Image *) NULL);
   assert(image->signature == MagickCoreSignature);
+  assert(exception != (ExceptionInfo *) NULL);
+  assert(exception->signature == MagickCoreSignature);
   if (IsEventLogging() != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
   if (status == MagickFalse)
     return(status);
+  /*
+    The encoder works in int coordinates.
+  */
+  if ((image->columns > (size_t) INT_MAX) || (image->rows > (size_t) INT_MAX))
+    ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
   /*
     Ensure sRGB colorspace.
   */
@@ -1446,10 +1427,6 @@ static MagickBooleanType WriteSIXELImage(const ImageInfo *image_info,
     }
   else
     {
-      MagickRealType
-        alpha,
-        beta;
-
       /*
         We have alpha: convert to palette with bilevel alpha and
         choose the most transparent colormap entry as "keycolor".
@@ -1460,57 +1437,31 @@ static MagickBooleanType WriteSIXELImage(const ImageInfo *image_info,
       for (i=0; i < (ssize_t) image->colors; i++)
         if (image->colormap[i].alpha != (double) OpaqueAlpha)
           {
-            if (opacity < 0)
-              {
-                opacity=i;
-                continue;
-              }
-            alpha=image->colormap[i].alpha;
-            beta=image->colormap[opacity].alpha;
-            if (alpha < beta)
+            if ((opacity < 0) ||
+                (image->colormap[i].alpha < image->colormap[opacity].alpha))
               opacity=i;
           }
       /*
-        If we didn't find one on the first pass, try again after
-        PaletteBilevelAlphaType conversion.
-      */
-      if (opacity == -1)
-        {
-          for (i=0; i < (ssize_t) image->colors; i++)
-            if (image->colormap[i].alpha != (double) OpaqueAlpha)
-              {
-                if (opacity < 0)
-                  {
-                    opacity=i;
-                    continue;
-                  }
-                alpha=image->colormap[i].alpha;
-                beta=image->colormap[opacity].alpha;
-                if (alpha < beta)
-                  opacity=i;
-              }
-        }
-      /*
-        NOTE: we do NOT overwrite the transparent colormap entry
-        with image->transparent_color here. The SIXEL encoder will
-        treat 'opacity' as a keycolor and skip drawing pixels with
-        that index, effectively making them transparent.
+        The SIXEL encoder treats 'opacity' as a keycolor and skips drawing
+        pixels with that index, leaving them transparent.
       */
     }
   /*
     SIXEL palette size limit.
   */
-  if (image->colors > SIXEL_PALETTE_MAX)
-    return(MagickFalse);
+  if ((image->colors == 0) || (image->colors > SIXEL_PALETTE_MAX))
+    ThrowWriterException(CoderError,"ColormapTooLarge");
   /*
     Build SIXEL palette (RGB only, no alpha).
   */
   for (i=0; i < (ssize_t) image->colors; i++)
   {
-    sixel_palette[3*i+0]=ScaleQuantumToChar((Quantum) image->colormap[i].red);
-    sixel_palette[3*i+1]=ScaleQuantumToChar((Quantum)
-      image->colormap[i].green);
-    sixel_palette[3*i+2]=ScaleQuantumToChar((Quantum) image->colormap[i].blue);
+    sixel_palette[3*i+0]=ScaleQuantumToChar(ClampToQuantum(
+      image->colormap[i].red));
+    sixel_palette[3*i+1]=ScaleQuantumToChar(ClampToQuantum(
+      image->colormap[i].green));
+    sixel_palette[3*i+2]=ScaleQuantumToChar(ClampToQuantum(
+      image->colormap[i].blue));
   }
   /*
     Define SIXEL pixels.
@@ -1532,27 +1483,23 @@ static MagickBooleanType WriteSIXELImage(const ImageInfo *image_info,
   for (y=0; y < (ssize_t) image->rows; y++)
   {
     q=GetVirtualPixels(image,0,y,image->columns,1,exception);
-    if (q == (Quantum *) NULL)
-      break;
+    if (q == (const Quantum *) NULL)
+      {
+        sixel_pixels=(sixel_pixel_t *) RelinquishMagickMemory(sixel_pixels);
+        output=(sixel_output_t *) RelinquishMagickMemory(output);
+        ThrowWriterException(CacheError,"UnableToGetPixelsFromCache");
+      }
     for (x=0; x < (ssize_t) image->columns; x++)
     {
       ssize_t
         index;

-      if ((image->alpha_trait & BlendPixelTrait) != 0 && opacity >= 0)
-        {
-          /*
-            If this pixel is transparent (or mostly transparent), assign the
-            keycolor index so sixel_encode_impl() can skip drawing it.
-          */
-          Quantum alpha_q = GetPixelAlpha(image,q);
-          if (alpha_q < (Quantum) (QuantumRange/2))
-            index=opacity;
-          else
-            index=(ssize_t) GetPixelIndex(image,q);
-        }
-      else
-        index=(ssize_t) GetPixelIndex(image,q); /* No alpha. */
+      index=(ssize_t) GetPixelIndex(image,q);
+      if (((image->alpha_trait & BlendPixelTrait) != 0) && (opacity >= 0) &&
+          (GetPixelAlpha(image,q) < (Quantum) (QuantumRange/2)))
+        index=opacity;
+      if ((index < 0) || (index >= (ssize_t) image->colors))
+        index=0;
       sixel_pixels[y*(ssize_t) image->columns+x]=(sixel_pixel_t) index;
       q+=(ptrdiff_t) GetPixelChannels(image);
     }
@@ -1565,6 +1512,9 @@ static MagickBooleanType WriteSIXELImage(const ImageInfo *image_info,
     sixel_palette,image->colors,(int) opacity,output);
   sixel_pixels=(sixel_pixel_t *) RelinquishMagickMemory(sixel_pixels);
   output=(sixel_output_t *) RelinquishMagickMemory(output);
+  if (status == MagickFalse)
+    (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
+      "UnableToWriteImage","`%s'",image->filename);
   if (CloseBlob(image) == MagickFalse)
     status=MagickFalse;
   return(status);