SDL_image: Fixed decoding CMYK JPG images

From edddd6af4a9bc98658ac8d7264fef246d5fbaeae Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Thu, 8 Jan 2026 11:30:37 -0800
Subject: [PATCH] Fixed decoding CMYK JPG images

Fixes https://github.com/libsdl-org/SDL_image/issues/410
---
 src/IMG_jpg.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/src/IMG_jpg.c b/src/IMG_jpg.c
index fd6ebb78..3a70ea88 100644
--- a/src/IMG_jpg.c
+++ b/src/IMG_jpg.c
@@ -384,7 +384,7 @@ static bool LIBJPEG_LoadJPG_IO(SDL_IOStream *src, struct loadjpeg_vars *vars)
         lib.jpeg_calc_output_dimensions(&vars->cinfo);
 
         /* Allocate an output surface to hold the image */
-        vars->surface = SDL_CreateSurface(vars->cinfo.output_width, vars->cinfo.output_height, SDL_PIXELFORMAT_BGRA32);
+        vars->surface = SDL_CreateSurface(vars->cinfo.output_width, vars->cinfo.output_height, SDL_PIXELFORMAT_RGBA32);
     } else {
         /* Set 24-bit RGB output */
         vars->cinfo.out_color_space = JCS_RGB;
@@ -416,6 +416,17 @@ static bool LIBJPEG_LoadJPG_IO(SDL_IOStream *src, struct loadjpeg_vars *vars)
     lib.jpeg_finish_decompress(&vars->cinfo);
     lib.jpeg_destroy_decompress(&vars->cinfo);
 
+    if (vars->cinfo.num_components == 4) {
+        // The CMYK image is essentially RGBA composed over black
+        SDL_Surface *output = SDL_CreateSurface(vars->cinfo.output_width, vars->cinfo.output_height, SDL_PIXELFORMAT_RGB24);
+        if (!output) {
+            return false;
+        }
+
+        SDL_BlitSurface(vars->surface, NULL, output, NULL);
+        SDL_DestroySurface(vars->surface);
+        vars->surface = output;
+    }
     return true;
 }