Commit 14cb40f5e for imagemagick.org

commit 14cb40f5ea7cf3000b7ec1367b238607c4704fa1
Author: Cristy <urban-warrior@imagemagick.org>
Date:   Sun Nov 29 09:14:11 2026 -0500

    palettes over 256 colors are now written as 24 or 32-bit

diff --git a/coders/dib.c b/coders/dib.c
index 6ff966bf5..1a6b0a70d 100644
--- a/coders/dib.c
+++ b/coders/dib.c
@@ -93,7 +93,7 @@ typedef struct _DIBInfo
     number_colors,
     colors_important;

-  unsigned short
+  unsigned int
     red_mask,
     green_mask,
     blue_mask,
@@ -114,6 +114,56 @@ typedef struct _DIBInfo
 */
 static MagickBooleanType
   WriteDIBImage(const ImageInfo *,Image *,ExceptionInfo *);
+
+/*
+  Channel bit-mask helpers for BI_BITFIELDS images.
+*/
+typedef struct _MaskInfo
+{
+  unsigned int
+    mask,
+    shift,
+    bits;
+} MaskInfo;
+
+static void GetMaskInfo(const unsigned int mask,MaskInfo *mask_info)
+{
+  unsigned int
+    value;
+
+  mask_info->mask=mask;
+  mask_info->shift=0;
+  mask_info->bits=0;
+  if (mask == 0)
+    return;
+  value=mask;
+  while ((value & 0x01U) == 0)
+  {
+    value>>=1;
+    mask_info->shift++;
+  }
+  while (value != 0)
+  {
+    value>>=1;
+    mask_info->bits++;
+  }
+}
+
+static unsigned char ScaleMaskedValue(const unsigned int word,
+  const MaskInfo *mask_info)
+{
+  unsigned int
+    maximum,
+    value;
+
+  if ((mask_info->bits == 0) || (mask_info->bits > 32))
+    return(0);
+  value=(word & mask_info->mask) >> mask_info->shift;
+  if (mask_info->bits >= 8)
+    return((unsigned char) (value >> (mask_info->bits-8)));
+  maximum=(1U << mask_info->bits)-1U;
+  return((unsigned char) (((value*255U)+(maximum/2U))/maximum));
+}

 /*
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -132,7 +182,7 @@ static MagickBooleanType
 %  The format of the DecodeImage method is:
 %
 %      MagickBooleanType DecodeImage(Image *image,
-%        const MagickBooleanType compression,unsigned char *pixels,
+%        const unsigned int compression,unsigned char *pixels,
 %        const size_t number_pixels)
 %
 %  A description of each parameter follows:
@@ -149,7 +199,7 @@ static MagickBooleanType
 %
 */
 static MagickBooleanType DecodeImage(Image *image,
-  const MagickBooleanType compression,unsigned char *pixels,
+  const unsigned int compression,unsigned char *pixels,
   const size_t number_pixels)
 {
 #define DibRgbCompression  0
@@ -251,6 +301,9 @@ static MagickBooleanType DecodeImage(Image *image,
             if (byte == EOF)
               return(MagickFalse);
             y+=byte;
+            if ((y >= (ssize_t) image->rows) ||
+                (x >= (ssize_t) image->columns))
+              return(MagickFalse);
             p=pixels+y*(ssize_t) image->columns+x;
             break;
           }
@@ -265,7 +318,7 @@ static MagickBooleanType DecodeImage(Image *image,
               {
                 byte=ReadBlobByte(image);
                 if (byte == EOF)
-                  break;
+                  return(MagickFalse);
                 *p++=(unsigned char) byte;
               }
             else
@@ -275,7 +328,7 @@ static MagickBooleanType DecodeImage(Image *image,
                   {
                     byte=ReadBlobByte(image);
                     if (byte == EOF)
-                      break;
+                      return(MagickFalse);
                   }
                 *p++=(unsigned char)
                   ((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f));
@@ -323,15 +376,15 @@ static MagickBooleanType DecodeImage(Image *image,
 %
 %  The format of the EncodeImage method is:
 %
-%    static MagickBooleanType EncodeImage(Image *image,
-%      const size_t bytes_per_line,const unsigned char *pixels,
-%      unsigned char *compressed_pixels)
+%    static size_t EncodeImage(Image *image,const size_t bytes_per_line,
+%      const unsigned char *pixels,unsigned char *compressed_pixels)
 %
 %  A description of each parameter follows:
 %
 %    o image:  The image.
 %
-%    o bytes_per_line: the number of bytes in a scanline of compressed pixels
+%    o bytes_per_line: the stride, in bytes, of a scanline of uncompressed
+%      pixels (only image->columns bytes of each scanline are encoded).
 %
 %    o pixels:  The address of a byte (8 bits) array of pixel data created by
 %      the compression process.
@@ -365,17 +418,17 @@ static size_t EncodeImage(Image *image,const size_t bytes_per_line,
   assert(compressed_pixels != (unsigned char *) NULL);
   if (IsEventLogging() != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
-  p=pixels;
   q=compressed_pixels;
   i=0;
   for (y=0; y < (ssize_t) image->rows; y++)
   {
-    for (x=0; x < (ssize_t) bytes_per_line; x+=i)
+    p=pixels+y*(ssize_t) bytes_per_line;
+    for (x=0; x < (ssize_t) image->columns; x+=i)
     {
       /*
         Determine runlength.
       */
-      for (i=1; ((x+i) < (ssize_t) bytes_per_line); i++)
+      for (i=1; ((x+i) < (ssize_t) image->columns); i++)
         if ((*(p+i) != *p) || (i == 255))
           break;
       *q++=(unsigned char) i;
@@ -387,7 +440,8 @@ static size_t EncodeImage(Image *image,const size_t bytes_per_line,
     */
     *q++=0x00;
     *q++=0x00;
-    if (SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows) == MagickFalse)
+    if (SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
+        image->rows) == MagickFalse)
       break;
   }
   /*
@@ -425,9 +479,9 @@ static size_t EncodeImage(Image *image,const size_t bytes_per_line,
 */
 static MagickBooleanType IsDIB(const unsigned char *magick,const size_t length)
 {
-  if (length < 2)
+  if (length < 4)
     return(MagickFalse);
-  if (memcmp(magick,"\050\000",2) == 0)
+  if (memcmp(magick,"\050\000\000\000",4) == 0)
     return(MagickTrue);
   return(MagickFalse);
 }
@@ -532,8 +586,6 @@ static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception)
   dib_info.height=ReadBlobLSBSignedLong(image);
   dib_info.planes=ReadBlobLSBShort(image);
   dib_info.bits_per_pixel=ReadBlobLSBShort(image);
-  if (dib_info.bits_per_pixel > 32)
-    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
   dib_info.compression=ReadBlobLSBLong(image);
   dib_info.image_size=ReadBlobLSBLong(image);
   dib_info.x_pixels=ReadBlobLSBLong(image);
@@ -543,22 +595,18 @@ static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception)
   if (EOFBlob(image) != MagickFalse)
     ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
       image->filename);
-  if ((dib_info.bits_per_pixel != 1) && (dib_info.bits_per_pixel != 4) &&
-      (dib_info.bits_per_pixel != 8) && (dib_info.bits_per_pixel != 16) &&
-      (dib_info.bits_per_pixel != 24) && (dib_info.bits_per_pixel != 32))
-    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
   if ((dib_info.compression == DibBitfieldsCompression) &&
       ((dib_info.bits_per_pixel == 16) || (dib_info.bits_per_pixel == 32)))
     {
-      dib_info.red_mask=(unsigned short) ReadBlobLSBLong(image);
-      dib_info.green_mask=(unsigned short) ReadBlobLSBLong(image);
-      dib_info.blue_mask=(unsigned short) ReadBlobLSBLong(image);
+      dib_info.red_mask=ReadBlobLSBLong(image);
+      dib_info.green_mask=ReadBlobLSBLong(image);
+      dib_info.blue_mask=ReadBlobLSBLong(image);
     }
   if (EOFBlob(image) != MagickFalse)
     ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
   if (dib_info.width <= 0)
     ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
-  if (dib_info.height == 0)
+  if ((dib_info.height == 0) || (dib_info.height < -2147483647))
     ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
   if (dib_info.planes != 1)
     ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne");
@@ -600,7 +648,7 @@ static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception)
     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
   if ((dib_info.image_size != 0U) && (dib_info.image_size > GetBlobSize(image)))
     ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
-  if ((dib_info.number_colors != 0) || (dib_info.bits_per_pixel < 8))
+  if ((dib_info.number_colors != 0) || (dib_info.bits_per_pixel < 16))
     {
       size_t
         one;
@@ -707,8 +755,8 @@ static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception)
       /*
         Convert run-length encoded raster pixels.
       */
-      status=DecodeImage(image,dib_info.compression ? MagickTrue : MagickFalse,
-        pixels,image->columns*image->rows);
+      status=DecodeImage(image,dib_info.compression,pixels,image->columns*
+        image->rows);
       if (status == MagickFalse)
         {
           pixel_info=RelinquishVirtualMemory(pixel_info);
@@ -851,15 +899,32 @@ static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception)
     }
     case 16:
     {
-      unsigned short
+      MaskInfo
+        blue_info,
+        green_info,
+        red_info;
+
+      unsigned int
         word;

       /*
-        Convert PseudoColor scanline.
+        Convert 16-bit DirectColor scanline (555 by default, else bitfields).
       */
       image->storage_class=DirectClass;
-      if (dib_info.compression == DibRle8Compression)
-        bytes_per_line=2*image->columns;
+      if ((dib_info.compression == DibBitfieldsCompression) &&
+          (dib_info.red_mask != 0) && (dib_info.green_mask != 0) &&
+          (dib_info.blue_mask != 0))
+        {
+          GetMaskInfo(dib_info.red_mask,&red_info);
+          GetMaskInfo(dib_info.green_mask,&green_info);
+          GetMaskInfo(dib_info.blue_mask,&blue_info);
+        }
+      else
+        {
+          GetMaskInfo(0x7c00U,&red_info);
+          GetMaskInfo(0x03e0U,&green_info);
+          GetMaskInfo(0x001fU,&blue_info);
+        }
       for (y=(ssize_t) image->rows-1; y >= 0; y--)
       {
         p=pixels+((ssize_t) image->rows-y-1)*(ssize_t) bytes_per_line;
@@ -868,26 +933,14 @@ static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception)
           break;
         for (x=0; x < (ssize_t) image->columns; x++)
         {
-          word=(*p++);
-          word|=(*p++ << 8);
-          if (dib_info.red_mask == 0)
-            {
-              SetPixelRed(image,ScaleCharToQuantum(ScaleColor5to8(
-                (unsigned char) ((word >> 10) & 0x1f))),q);
-              SetPixelGreen(image,ScaleCharToQuantum(ScaleColor5to8(
-                (unsigned char) ((word >> 5) & 0x1f))),q);
-              SetPixelBlue(image,ScaleCharToQuantum(ScaleColor5to8(
-                (unsigned char) (word & 0x1f))),q);
-            }
-          else
-            {
-              SetPixelRed(image,ScaleCharToQuantum(ScaleColor5to8(
-                (unsigned char) ((word >> 11) & 0x1f))),q);
-              SetPixelGreen(image,ScaleCharToQuantum(ScaleColor6to8(
-                (unsigned char) ((word >> 5) & 0x3f))),q);
-              SetPixelBlue(image,ScaleCharToQuantum(ScaleColor5to8(
-                (unsigned char) (word & 0x1f))),q);
-            }
+          word=(unsigned int) (*p++);
+          word|=(unsigned int) (*p++) << 8;
+          SetPixelRed(image,ScaleCharToQuantum(ScaleMaskedValue(word,
+            &red_info)),q);
+          SetPixelGreen(image,ScaleCharToQuantum(ScaleMaskedValue(word,
+            &green_info)),q);
+          SetPixelBlue(image,ScaleCharToQuantum(ScaleMaskedValue(word,
+            &blue_info)),q);
           q+=(ptrdiff_t) GetPixelChannels(image);
         }
         if (SyncAuthenticPixels(image,exception) == MagickFalse)
@@ -945,10 +998,17 @@ static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception)
       int
         c;

+      MagickBooleanType
+        apply_mask;
+
       /*
-        Handle ICO mask.
+        Handle ICO mask (a 32-bit image carries its own alpha channel).
       */
-      for (y=0; y < (ssize_t) image->rows; y++)
+      apply_mask=dib_info.bits_per_pixel != 32 ? MagickTrue : MagickFalse;
+      if ((apply_mask != MagickFalse) &&
+          (image->alpha_trait == UndefinedPixelTrait))
+        (void) SetImageAlpha(image,OpaqueAlpha,exception);
+      for (y=(ssize_t) image->rows-1; y >= 0; y--)
       {
         q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
         if (q == (Quantum *) NULL)
@@ -956,24 +1016,22 @@ static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception)
         for (x=0; x < ((ssize_t) image->columns-7); x+=8)
         {
           c=ReadBlobByte(image);
-          for (bit=0; bit < 8; bit++)
-          {
-            if (c & (0x80 >> bit))
-              image->alpha_trait=BlendPixelTrait;
-            SetPixelAlpha(image,c & (0x80 >> bit) ? TransparentAlpha :
-              OpaqueAlpha,q+x*(ssize_t) GetPixelChannels(image)+bit);
-          }
+          if (c == EOF)
+            c=0;
+          if (apply_mask != MagickFalse)
+            for (bit=0; bit < 8; bit++)
+              SetPixelAlpha(image,c & (0x80 >> bit) ? TransparentAlpha :
+                OpaqueAlpha,q+(x+bit)*(ssize_t) GetPixelChannels(image));
         }
         if ((image->columns % 8) != 0)
           {
             c=ReadBlobByte(image);
-            for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)
-            {
-              if (c & (0x80 >> bit))
-                image->alpha_trait=BlendPixelTrait;
-              SetPixelAlpha(image,c & (0x80 >> bit) ? TransparentAlpha :
-                OpaqueAlpha,q+x*(ssize_t) GetPixelChannels(image)+bit);
-            }
+            if (c == EOF)
+              c=0;
+            if (apply_mask != MagickFalse)
+              for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)
+                SetPixelAlpha(image,c & (0x80 >> bit) ? TransparentAlpha :
+                  OpaqueAlpha,q+(x+bit)*(ssize_t) GetPixelChannels(image));
           }
         if (image->columns % 32)
           for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++)
@@ -1000,6 +1058,8 @@ static Image *ReadDIBImage(const ImageInfo *image_info,ExceptionInfo *exception)
           image=DestroyImage(image);
           image=flipped_image;
         }
+      else
+        status=MagickFalse;
     }
   if (CloseBlob(image) == MagickFalse)
     status=MagickFalse;
@@ -1154,6 +1214,7 @@ static MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image,
   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
   if (status == MagickFalse)
     return(status);
+  (void) memset(&dib_info,0,sizeof(dib_info));
   if (((image->columns << 3) != (size_t) ((int) (image->columns << 3))) ||
       ((image->rows << 3) != (size_t) ((int) (image->rows << 3))))
     ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
@@ -1162,7 +1223,7 @@ static MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image,
   */
   if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
     (void) TransformImageColorspace(image,sRGBColorspace,exception);
-  if (image->storage_class == DirectClass)
+  if ((image->storage_class == DirectClass) || (image->colors > 256))
     {
       /*
         Full color DIB raster.
@@ -1224,6 +1285,7 @@ static MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image,
   if (pixels == (unsigned char *) NULL)
     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
   (void) memset(pixels,0,length);
+  status=MagickTrue;
   switch (dib_info.bits_per_pixel)
   {
     case 1:
@@ -1239,7 +1301,10 @@ static MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image,
       {
         p=GetVirtualPixels(image,0,y,image->columns,1,exception);
         if (p == (const Quantum *) NULL)
-          break;
+          {
+            status=MagickFalse;
+            break;
+          }
         q=pixels+((ssize_t) image->rows-y-1)*(ssize_t) bytes_per_line;
         bit=0;
         byte=0;
@@ -1279,7 +1344,10 @@ static MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image,
       {
         p=GetVirtualPixels(image,0,y,image->columns,1,exception);
         if (p == (const Quantum *) NULL)
-          break;
+          {
+            status=MagickFalse;
+            break;
+          }
         q=pixels+((ssize_t) image->rows-y-1)*(ssize_t) bytes_per_line;
         for (x=0; x < (ssize_t) image->columns; x++)
         {
@@ -1306,15 +1374,18 @@ static MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image,
       {
         p=GetVirtualPixels(image,0,y,image->columns,1,exception);
         if (p == (const Quantum *) NULL)
-          break;
+          {
+            status=MagickFalse;
+            break;
+          }
         q=pixels+((ssize_t) image->rows-y-1)*(ssize_t) bytes_per_line;
         for (x=0; x < (ssize_t) image->columns; x++)
         {
           word=(unsigned short) ((ScaleColor8to5((unsigned char)
             ScaleQuantumToChar(GetPixelRed(image,p))) << 11) | (ScaleColor8to6(
             (unsigned char) ScaleQuantumToChar(GetPixelGreen(image,p))) << 5) |
-            (ScaleColor8to5((unsigned char) ScaleQuantumToChar((unsigned char)
-            GetPixelBlue(image,p)) << 0)));
+            ScaleColor8to5((unsigned char) ScaleQuantumToChar(
+            GetPixelBlue(image,p))));
           *q++=(unsigned char)(word & 0xff);
           *q++=(unsigned char)(word >> 8);
           p+=(ptrdiff_t) GetPixelChannels(image);
@@ -1338,7 +1409,10 @@ static MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image,
       {
         p=GetVirtualPixels(image,0,y,image->columns,1,exception);
         if (p == (const Quantum *) NULL)
-          break;
+          {
+            status=MagickFalse;
+            break;
+          }
         q=pixels+((ssize_t) image->rows-y-1)*(ssize_t) bytes_per_line;
         for (x=0; x < (ssize_t) image->columns; x++)
         {
@@ -1360,8 +1434,14 @@ static MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image,
       break;
     }
   }
+  if (status == MagickFalse)
+    {
+      pixels=(unsigned char *) RelinquishMagickMemory(pixels);
+      (void) CloseBlob(image);
+      return(MagickFalse);
+    }
   if (dib_info.bits_per_pixel == 8)
-    if (image_info->compression != NoCompression)
+    if (image_info->compression == RLECompression)
       {
         /*
           Convert run-length encoded raster pixels.
@@ -1394,7 +1474,7 @@ static MagickBooleanType WriteDIBImage(const ImageInfo *image_info,Image *image,
   (void) WriteBlobLSBLong(image,dib_info.y_pixels);
   (void) WriteBlobLSBLong(image,dib_info.number_colors);
   (void) WriteBlobLSBLong(image,dib_info.colors_important);
-  if (image->storage_class == PseudoClass)
+  if ((dib_info.bits_per_pixel <= 8) || (dib_info.bits_per_pixel == 16))
     {
       if (dib_info.bits_per_pixel <= 8)
         {