From 1ad30e4e7724ca8afc126b2c1088425d57a423bc Mon Sep 17 00:00:00 2001 From: Daniel Gibson Date: Mon, 9 Apr 2018 01:24:17 +0200 Subject: [PATCH] stb_image_write.h: Fix jpg flipping for non-multiple-of-8 sizes JPG always encodes 8x8 pixel blocks. If the input image does not have a width or height that's a multiple of 8, the last column or row is just used multiple times for the remaining pixels of the block. The original code first calculated p (the index into the pixel data) with the "imaginary" row/colum (that might be up to 7 pixels too far into each direction) and then subtracted the necessary amount of bytes it if row >= height or col >= width. That was a bit cryptic (IMHO), and didn't get more readable/obvious when vertical flipping was added - which introduced a bug, by not taking stbi__flip_vertically_on_write into account when adjusting p for row >= height... The code should be more obvious (and less buggy) now. This fixes bug #592 --- stb_image_write.h | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/stb_image_write.h b/stb_image_write.h index c05e958..a98e3d1 100644 --- a/stb_image_write.h +++ b/stb_image_write.h @@ -1424,14 +1424,16 @@ static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, in float YDU[64], UDU[64], VDU[64]; for(row = y, pos = 0; row < y+8; ++row) { for(col = x; col < x+8; ++col, ++pos) { - int p = (stbi__flip_vertically_on_write ? height-1-row : row)*width*comp + col*comp; float r, g, b; - if(row >= height) { - p -= width*comp*(row+1 - height); - } - if(col >= width) { - p -= comp*(col+1 - width); + int p; + if(row < height) { + p = (stbi__flip_vertically_on_write ? (height-1-row) : row)*width*comp; + } else { + // row >= height => use last input row (=> first if flipping) + p = stbi__flip_vertically_on_write ? 0 : ((height-1)*width*comp); } + // if col >= width => use pixel from last input column + p += ((col < width) ? col : (width-1))*comp; r = imageData[p+0]; g = imageData[p+ofsG];