Skip to content

Commit 25cdca2

Browse files
committed
Save non-alpha pngs as RGB not RGBA
1 parent b9cf035 commit 25cdca2

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

src/IMG_png.c

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -766,14 +766,41 @@ static int IMG_SavePNG_RW_miniz(SDL_Surface *surface, SDL_RWops *dst)
766766
return IMG_SetError("Passed NULL dst");
767767
}
768768

769-
if (surface->format->format == png_format) {
770-
png = tdefl_write_image_to_png_file_in_memory(surface->pixels, surface->w, surface->h, surface->format->BytesPerPixel, surface->pitch, &size);
771-
} else {
772-
SDL_Surface *cvt = SDL_ConvertSurfaceFormat(surface, png_format, 0);
773-
if (cvt) {
774-
png = tdefl_write_image_to_png_file_in_memory(cvt->pixels, cvt->w, cvt->h, cvt->format->BytesPerPixel, cvt->pitch, &size);
775-
SDL_FreeSurface(cvt);
769+
// TODO:
770+
// how to handle indexed+alpha images?
771+
// how to handle colorkey?
772+
Uint32 cvt_fmt = SDL_ISPIXELFORMAT_ALPHA(surface->format->format) ? png_format : SDL_PIXELFORMAT_RGB24;
773+
SDL_Surface *cvt = NULL;
774+
Uint8 *pixels = surface->pixels;
775+
int bpp = surface->format->BytesPerPixel;
776+
int pitch = surface->pitch;
777+
if (surface->format->format != cvt_fmt) {
778+
cvt = SDL_ConvertSurfaceFormat(surface, cvt_fmt, 0);
779+
pixels = cvt ? cvt->pixels : NULL;
780+
bpp = cvt ? cvt->format->BytesPerPixel : 0;
781+
pitch = cvt ? cvt->pitch : 0;
782+
}
783+
if (pixels) {
784+
int w = surface->w;
785+
int h = surface->h;
786+
int tightened_pitch = bpp * w;
787+
if (pitch != tightened_pitch) {
788+
/* There is extra padding that we need to get rid of */
789+
Uint8 *tightened_pixels = SDL_malloc(tightened_pitch * h);
790+
if (tightened_pixels) {
791+
for (int y = 0; y < h; y++) {
792+
memcpy(tightened_pixels + y * tightened_pitch, pixels + y * pitch, tightened_pitch);
793+
}
794+
png = tdefl_write_image_to_png_file_in_memory(tightened_pixels, w, h, bpp, tightened_pitch, &size);
795+
SDL_free(tightened_pixels);
796+
}
776797
}
798+
else {
799+
png = tdefl_write_image_to_png_file_in_memory(pixels, w, h, bpp, pitch, &size);
800+
}
801+
}
802+
if (cvt) {
803+
SDL_FreeSurface(cvt);
777804
}
778805
if (png) {
779806
if (SDL_RWwrite(dst, png, size, 1)) {

0 commit comments

Comments
 (0)