# SDL\_image: Fix loading greyscale with libpng for 1, 2, 4 and 8 bit formats getting colors off by one

**URL:** <https://discourse.libsdl.org/t/sdl-image-fix-loading-greyscale-with-libpng-for-1-2-4-and-8-bit-formats-getting-colors-off-by-one/69744>\
**Category:** SDL Commits\
**Created:** [November 3, 2026, 4:22pm UTC](https://discourse.libsdl.org/t/sdl-image-fix-loading-greyscale-with-libpng-for-1-2-4-and-8-bit-formats-getting-colors-off-by-one/69744 "2026-11-03T16:22:55Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![SDLPushPostBot](https://discourse.libsdl.org/user_avatar/discourse.libsdl.org/sdlpushpostbot/32/4370_2.png) [@SDLPushPostBot](https://discourse.libsdl.org/u/SDLPushPostBot)\
**Post date:** [November 3, 2026, 4:22pm UTC](https://discourse.libsdl.org/t/sdl-image-fix-loading-greyscale-with-libpng-for-1-2-4-and-8-bit-formats-getting-colors-off-by-one/69744/1 "2026-11-03T16:22:55Z")

</div>

> <https://github.com/libsdl-org/SDL_image/commit/641e48ded020bae84d8bf7aed37174279eb914b9>

```diff
From 641e48ded020bae84d8bf7aed37174279eb914b9 Mon Sep 17 00:00:00 2001
From: Mathieu Ropert <[EMAIL REDACTED]>
Date: Fri, 30 Oct 2026 16:48:28 +0100
Subject: [PATCH] Fix loading greyscale with libpng for 1, 2, 4 and 8 bit
 formats getting colors off by one

---
 src/IMG_libpng.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/IMG_libpng.c b/src/IMG_libpng.c
index eb3eb1256..3fe590692 100644
--- a/src/IMG_libpng.c
+++ b/src/IMG_libpng.c
@@ -480,9 +480,9 @@ static bool LIBPNG_LoadPNG_IO_Internal(SDL_IOStream *src, struct png_load_vars *
         }
 
         for (int i = 0; i < palette->ncolors; i++) {
- palette->colors[i].r = (i * 255) / palette->ncolors;
- palette->colors[i].g = (i * 255) / palette->ncolors;
- palette->colors[i].b = (i * 255) / palette->ncolors;
+ palette->colors[i].r = (i * 255) / (palette->ncolors - 1);
+ palette->colors[i].g = (i * 255) / (palette->ncolors - 1);
+ palette->colors[i].b = (i * 255) / (palette->ncolors - 1);
             palette->colors[i].a = 255;
         }
     }

```
