[Image-SIG] Patch for libImaging/Offset.c

Charles G Waldman cgw@pgt.com
Sun, 1 Nov 1998 01:47:26 -0500 (EST)


I found that using the Image.offset method frequently gave me
corrupted images and core-dumps.  I tracked the problem down to 
this code:

	int yi = (y - yoffset) % im->ysize;
	int xi = (x - xoffset) % im->xsize;
	imOut->image[y][x] = im->image[yi][xi];

The problem is that when (x - xoffset) < 0 then xi is also < 0, since
negative%positive is still negative.  (ditto for y,yi)

The patch below fixes this problem; it replaces the subtraction with
an addition, making sure that the offsets used are positive.  Since
the checks are done outside the loops there is no penalty.  Because
everything is being done using modular arithmetic, xoffset is
equivalent to xoffset + im->xsize.


--- Imaging-0.3b2/libImaging/Offset.c	1998/11/01 05:55:58	1.1
+++ Imaging-0.3b2/libImaging/Offset.c	1998/11/01 06:35:20
@@ -6,6 +6,7 @@
  *
  * history:
  *	96-07-22 fl:	Created
+ *	98-11-01 cgw@pgt.com: Fixed negative-array index bug
  *
  * Copyright (c) Fredrik Lundh 1996.
  * Copyright (c) Secret Labs AB 1997.
@@ -32,11 +33,24 @@
 
     ImagingCopyInfo(imOut, im);
 
+    /* Set up offsets so they are added rather than subtracted,  avoiding  
+     * negative offsets, which can lead to negative values of xi, yi below
+     */
+    xoffset %= im->xsize;
+    xoffset = im->xsize - xoffset;
+    if (xoffset<0)
+	xoffset += im->xsize;
+    
+    yoffset %=  im->ysize;
+    yoffset = im->ysize - yoffset;
+    if (yoffset<0)
+	yoffset += im->ysize;
+       
 #define	OFFSET(image)\
     for (y = 0; y < im->ysize; y++)\
 	for (x = 0; x < im->xsize; x++) {\
-	    int yi = (y - yoffset) % im->ysize;\
-	    int xi = (x - xoffset) % im->xsize;\
+	    int yi = (y + yoffset) % im->ysize;\
+	    int xi = (x + xoffset) % im->xsize;\
 	    imOut->image[y][x] = im->image[yi][xi];\
 	}