From: Cristy <urban-warrior@imagemagick.org>
Date: Mon, 21 Feb 2022 11:55:23 -0500
Subject: CVE-2023-34151

This is a prerequist for fixing it

magick produces incorrect result possibly due to overflow

bug: https://github.com/ImageMagick/ImageMagick/issues/4870
origin: https://github.com/ImageMagick/ImageMagick6/commit/8b7b17c8fef72dab479e6ca676676d8c5e395dd6
---
 coders/txt.c           | 24 ++++++++++++------------
 magick/image-private.h | 11 +++++++++++
 2 files changed, 23 insertions(+), 12 deletions(-)

diff --git a/coders/txt.c b/coders/txt.c
index 0e5c794..bca071f 100644
--- a/coders/txt.c
+++ b/coders/txt.c
@@ -573,18 +573,18 @@ static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
             green+=(range+1)/2.0;
             blue+=(range+1)/2.0;
           }
-        pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny)
-          MagickMax(red+0.5,0.0),range);
-        pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny)
-          MagickMax(green+0.5,0.0),range);
-        pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny)
-          MagickMax(blue+0.5,0.0),range);
-        pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny)
-          MagickMax(index+0.5,0.0),range);
-        pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny)
-          MagickMax(opacity+0.5,0.0),range);
-        q=GetAuthenticPixels(image,CastDoubleToLong(x_offset),
-          CastDoubleToLong(y_offset),1,1,exception);
+        pixel.red=(MagickRealType) ScaleAnyToQuantum(CastDoubleToQuantumAny(
+          red),range);
+        pixel.green=(MagickRealType) ScaleAnyToQuantum(CastDoubleToQuantumAny(
+          green),range);
+        pixel.blue=(MagickRealType) ScaleAnyToQuantum(CastDoubleToQuantumAny(
+          blue),range);
+        pixel.index=(MagickRealType) ScaleAnyToQuantum(CastDoubleToQuantumAny(
+          index),range);
+        pixel.opacity=(MagickRealType) ScaleAnyToQuantum(CastDoubleToQuantumAny(
+          opacity),range);
+        q=GetAuthenticPixels(image,CastDoubleToLong(x_offset),CastDoubleToLong(
+          y_offset),1,1,exception);
         if (q == (PixelPacket *) NULL)
           {
             status=MagickFalse;
diff --git a/magick/image-private.h b/magick/image-private.h
index b269f33..fc7d4b4 100644
--- a/magick/image-private.h
+++ b/magick/image-private.h
@@ -84,6 +84,17 @@ static inline size_t CastDoubleToUnsigned(const double x)
   return((size_t) x);
 }
 
+static inline QuantumAny CastDoubleToQuantumAny(const double x)
+{
+  if (IsNaN(x) != 0)
+    return(0);
+  if (x > ((double) ((QuantumAny) ~0)))
+    return((QuantumAny) ~0);
+  if (x < 0.0)
+    return(0.0);
+  return((QuantumAny) (x+0.5));
+}
+
 static inline double DegreesToRadians(const double degrees)
 {
   return((double) (MagickPI*degrees/180.0));
