From d5df600d43c8706df513a3273d09aee6f54a9233 Mon Sep 17 00:00:00 2001
From: Cristy <urban-warrior@imagemagick.org>
Date: Mon, 14 Oct 2019 19:56:17 -0400
Subject: [PATCH] https://github.com/ImageMagick/ImageMagick/issues/1754

---
 magick/quantize.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/magick/quantize.c b/magick/quantize.c
index 37f58914a..1d8cc61ff 100644
--- a/magick/quantize.c
+++ b/magick/quantize.c
@@ -3207,6 +3207,15 @@ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
 extern "C" {
 #endif
 
+static inline double ConstrainPixelIntensity(double x)
+{
+  if (x < (double) -(SSIZE_MAX-512))
+    return((double) -(SSIZE_MAX-512));
+  if (x > (double) (SSIZE_MAX-512))
+    return((double) (SSIZE_MAX-512));
+  return(x);
+}
+
 static int IntensityCompare(const void *x,const void *y)
 {
   PixelPacket
@@ -3218,8 +3227,8 @@ static int IntensityCompare(const void *x,const void *y)
 
   color_1=(PixelPacket *) x;
   color_2=(PixelPacket *) y;
-  intensity=(ssize_t) PixelPacketIntensity(color_1)-
-    (ssize_t) PixelPacketIntensity(color_2);
+  intensity=(ssize_t) ConstrainPixelIntensity(PixelPacketIntensity(color_1))-
+    (ssize_t) ConstrainPixelIntensity(PixelPacketIntensity(color_2));
   return((int) intensity);
 }
 
