|
21 | 21 | #include "SDL_internal.h" |
22 | 22 |
|
23 | 23 | #include "SDL_stb_c.h" |
24 | | - |
| 24 | +#include "SDL_surface_c.h" |
25 | 25 |
|
26 | 26 | // We currently only support JPEG, but we could add other image formats if we wanted |
27 | 27 | #ifdef SDL_HAVE_STB |
|
59 | 59 | #define STB_IMAGE_IMPLEMENTATION |
60 | 60 | #include "stb_image.h" |
61 | 61 |
|
| 62 | +#undef memcpy |
| 63 | +#define STB_IMAGE_WRITE_IMPLEMENTATION |
| 64 | +#define STB_IMAGE_WRITE_STATIC |
| 65 | +#define STBI_WRITE_NO_STDIO |
| 66 | +#define STBIW_ASSERT SDL_assert |
| 67 | +#include "stb_image_write.h" |
| 68 | + |
62 | 69 | #undef memset |
63 | 70 | #endif |
64 | 71 |
|
@@ -119,3 +126,68 @@ bool SDL_ConvertPixels_STB(int width, int height, |
119 | 126 | return SDL_SetError("SDL not built with STB image support"); |
120 | 127 | #endif |
121 | 128 | } |
| 129 | + |
| 130 | +#ifdef SDL_HAVE_STB |
| 131 | +static void SDL_STBWriteFunc(void *context, void *data, int size) |
| 132 | +{ |
| 133 | + SDL_WriteIO(context, data, size); |
| 134 | +} |
| 135 | +#endif |
| 136 | + |
| 137 | +bool SDL_SavePNG_IO(SDL_Surface *surface, SDL_IOStream *dst, bool closeio) |
| 138 | +{ |
| 139 | +#ifdef SDL_HAVE_STB |
| 140 | + bool retval = true; |
| 141 | + |
| 142 | + // Make sure we have somewhere to save |
| 143 | + if (!SDL_SurfaceValid(surface)) { |
| 144 | + retval = SDL_InvalidParamError("surface"); |
| 145 | + goto done; |
| 146 | + } |
| 147 | + if (!dst) { |
| 148 | + retval = SDL_InvalidParamError("dst"); |
| 149 | + goto done; |
| 150 | + } |
| 151 | + |
| 152 | + bool free_surface = false; |
| 153 | + if (surface->format != SDL_PIXELFORMAT_ABGR8888) { |
| 154 | + surface = SDL_ConvertSurface(surface, SDL_PIXELFORMAT_ABGR8888); |
| 155 | + if (!surface) { |
| 156 | + retval = false; |
| 157 | + goto done; |
| 158 | + } |
| 159 | + free_surface = true; |
| 160 | + } |
| 161 | + |
| 162 | + if (!stbi_write_png_to_func(SDL_STBWriteFunc, dst, surface->w, surface->h, 4, surface->pixels, surface->pitch)) { |
| 163 | + retval = SDL_SetError("Failed to write PNG"); |
| 164 | + } |
| 165 | + |
| 166 | + if (free_surface) { |
| 167 | + SDL_DestroySurface(surface); |
| 168 | + } |
| 169 | + |
| 170 | +done: |
| 171 | + if (dst && closeio) { |
| 172 | + retval = SDL_CloseIO(dst); |
| 173 | + } |
| 174 | + |
| 175 | + return retval; |
| 176 | +#else |
| 177 | + return SDL_SetError("SDL not built with STB image write support"); |
| 178 | +#endif |
| 179 | +} |
| 180 | + |
| 181 | +bool SDL_SavePNG(SDL_Surface *surface, const char *file) |
| 182 | +{ |
| 183 | +#ifdef SDL_HAVE_STB |
| 184 | + SDL_IOStream *stream = SDL_IOFromFile(file, "wb"); |
| 185 | + if (!stream) { |
| 186 | + return false; |
| 187 | + } |
| 188 | + |
| 189 | + return SDL_SavePNG_IO(surface, stream, true); |
| 190 | +#else |
| 191 | + return SDL_SetError("SDL not built with STB image write support"); |
| 192 | +#endif |
| 193 | +} |
0 commit comments