SDL_bmp.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. /*
  20. Code to load and save surfaces in Windows BMP format.
  21. Why support BMP format? Well, it's a native format for Windows, and
  22. most image processing programs can read and write it. It would be nice
  23. to be able to have at least one image format that we can natively load
  24. and save, and since PNG is so complex that it would bloat the library,
  25. BMP is a good alternative.
  26. This code currently supports Win32 DIBs in uncompressed 8 and 24 bpp.
  27. */
  28. #include "SDL_pixels_c.h"
  29. #include "SDL_surface_c.h"
  30. #define SAVE_32BIT_BMP
  31. // Compression encodings for BMP files
  32. #ifndef BI_RGB
  33. #define BI_RGB 0
  34. #define BI_RLE8 1
  35. #define BI_RLE4 2
  36. #define BI_BITFIELDS 3
  37. #endif
  38. // Logical color space values for BMP files
  39. // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/eb4bbd50-b3ce-4917-895c-be31f214797f
  40. #ifndef LCS_WINDOWS_COLOR_SPACE
  41. // 0x57696E20 == "Win "
  42. #define LCS_WINDOWS_COLOR_SPACE 0x57696E20
  43. #endif
  44. #ifndef LCS_sRGB
  45. // 0x73524742 == "sRGB"
  46. #define LCS_sRGB 0x73524742
  47. #endif
  48. // Logical/physical color relationship
  49. // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/9fec0834-607d-427d-abd5-ab240fb0db38
  50. #ifndef LCS_GM_GRAPHICS
  51. #define LCS_GM_GRAPHICS 0x00000002
  52. #endif
  53. static bool readRlePixels(SDL_Surface *surface, SDL_IOStream *src, int isRle8)
  54. {
  55. /*
  56. | Sets the surface pixels from src. A bmp image is upside down.
  57. */
  58. int pitch = surface->pitch;
  59. int height = surface->h;
  60. Uint8 *start = (Uint8 *)surface->pixels;
  61. Uint8 *end = start + (height * pitch);
  62. Uint8 *bits = end - pitch, *spot;
  63. int ofs = 0;
  64. Uint8 ch;
  65. Uint8 needsPad;
  66. const int pixels_per_byte = (isRle8 ? 1 : 2);
  67. #define COPY_PIXEL(x) \
  68. spot = &bits[ofs++]; \
  69. if (spot >= start && spot < end) \
  70. *spot = (x)
  71. for (;;) {
  72. if (!SDL_ReadU8(src, &ch)) {
  73. return false;
  74. }
  75. /*
  76. | encoded mode starts with a run length, and then a byte
  77. | with two colour indexes to alternate between for the run
  78. */
  79. if (ch) {
  80. Uint8 pixelvalue;
  81. if (!SDL_ReadU8(src, &pixelvalue)) {
  82. return false;
  83. }
  84. ch /= pixels_per_byte;
  85. do {
  86. COPY_PIXEL(pixelvalue);
  87. } while (--ch);
  88. } else {
  89. /*
  90. | A leading zero is an escape; it may signal the end of the bitmap,
  91. | a cursor move, or some absolute data.
  92. | zero tag may be absolute mode or an escape
  93. */
  94. if (!SDL_ReadU8(src, &ch)) {
  95. return false;
  96. }
  97. switch (ch) {
  98. case 0: // end of line
  99. ofs = 0;
  100. bits -= pitch; // go to previous
  101. break;
  102. case 1: // end of bitmap
  103. return true; // success!
  104. case 2: // delta
  105. if (!SDL_ReadU8(src, &ch)) {
  106. return false;
  107. }
  108. ofs += ch / pixels_per_byte;
  109. if (!SDL_ReadU8(src, &ch)) {
  110. return false;
  111. }
  112. bits -= ((ch / pixels_per_byte) * pitch);
  113. break;
  114. default: // no compression
  115. ch /= pixels_per_byte;
  116. needsPad = (ch & 1);
  117. do {
  118. Uint8 pixelvalue;
  119. if (!SDL_ReadU8(src, &pixelvalue)) {
  120. return false;
  121. }
  122. COPY_PIXEL(pixelvalue);
  123. } while (--ch);
  124. // pad at even boundary
  125. if (needsPad && !SDL_ReadU8(src, &ch)) {
  126. return false;
  127. }
  128. break;
  129. }
  130. }
  131. }
  132. }
  133. static void CorrectAlphaChannel(SDL_Surface *surface)
  134. {
  135. // Check to see if there is any alpha channel data
  136. bool hasAlpha = false;
  137. #if SDL_BYTEORDER == SDL_BIG_ENDIAN
  138. int alphaChannelOffset = 0;
  139. #else
  140. int alphaChannelOffset = 3;
  141. #endif
  142. Uint8 *alpha = ((Uint8 *)surface->pixels) + alphaChannelOffset;
  143. Uint8 *end = alpha + surface->h * surface->pitch;
  144. while (alpha < end) {
  145. if (*alpha != 0) {
  146. hasAlpha = true;
  147. break;
  148. }
  149. alpha += 4;
  150. }
  151. if (!hasAlpha) {
  152. alpha = ((Uint8 *)surface->pixels) + alphaChannelOffset;
  153. while (alpha < end) {
  154. *alpha = SDL_ALPHA_OPAQUE;
  155. alpha += 4;
  156. }
  157. }
  158. }
  159. bool SDL_IsBMP(SDL_IOStream *src)
  160. {
  161. Sint64 start;
  162. Uint8 magic[2];
  163. bool is_BMP;
  164. is_BMP = false;
  165. start = SDL_TellIO(src);
  166. if (start >= 0) {
  167. if (SDL_ReadIO(src, magic, sizeof(magic)) == sizeof(magic)) {
  168. if (magic[0] == 'B' && magic[1] == 'M') {
  169. is_BMP = true;
  170. }
  171. }
  172. SDL_SeekIO(src, start, SDL_IO_SEEK_SET);
  173. }
  174. return is_BMP;
  175. }
  176. SDL_Surface *SDL_LoadBMP_IO(SDL_IOStream *src, bool closeio)
  177. {
  178. bool was_error = true;
  179. Sint64 fp_offset = 0;
  180. int i, pad;
  181. SDL_Surface *surface;
  182. Uint32 Rmask = 0;
  183. Uint32 Gmask = 0;
  184. Uint32 Bmask = 0;
  185. Uint32 Amask = 0;
  186. Uint8 *bits;
  187. Uint8 *top, *end;
  188. bool topDown;
  189. bool haveRGBMasks = false;
  190. bool haveAlphaMask = false;
  191. bool correctAlpha = false;
  192. // The Win32 BMP file header (14 bytes)
  193. // char magic[2];
  194. // Uint32 bfSize;
  195. // Uint16 bfReserved1;
  196. // Uint16 bfReserved2;
  197. Uint32 bfOffBits;
  198. // The Win32 BITMAPINFOHEADER struct (40 bytes)
  199. Uint32 biSize;
  200. Sint32 biWidth = 0;
  201. Sint32 biHeight = 0;
  202. // Uint16 biPlanes;
  203. Uint16 biBitCount = 0;
  204. Uint32 biCompression = 0;
  205. // Uint32 biSizeImage;
  206. // Sint32 biXPelsPerMeter;
  207. // Sint32 biYPelsPerMeter;
  208. Uint32 biClrUsed = 0;
  209. // Uint32 biClrImportant;
  210. // Make sure we are passed a valid data source
  211. surface = NULL;
  212. CHECK_PARAM(!src) {
  213. SDL_InvalidParamError("src");
  214. goto done;
  215. }
  216. // Read in the BMP file header
  217. fp_offset = SDL_TellIO(src);
  218. if (fp_offset < 0) {
  219. goto done;
  220. }
  221. SDL_ClearError();
  222. if (!SDL_IsBMP(src)) {
  223. SDL_SetError("File is not a Windows BMP file");
  224. goto done;
  225. }
  226. if (!SDL_ReadU16LE(src, NULL /* magic (already checked) */) ||
  227. !SDL_ReadU32LE(src, NULL /* bfSize */) ||
  228. !SDL_ReadU16LE(src, NULL /* bfReserved1 */) ||
  229. !SDL_ReadU16LE(src, NULL /* bfReserved2 */) ||
  230. !SDL_ReadU32LE(src, &bfOffBits)) {
  231. goto done;
  232. }
  233. // Read the Win32 BITMAPINFOHEADER
  234. if (!SDL_ReadU32LE(src, &biSize)) {
  235. goto done;
  236. }
  237. if (biSize == 12) { // really old BITMAPCOREHEADER
  238. Uint16 biWidth16, biHeight16;
  239. if (!SDL_ReadU16LE(src, &biWidth16) ||
  240. !SDL_ReadU16LE(src, &biHeight16) ||
  241. !SDL_ReadU16LE(src, NULL /* biPlanes */) ||
  242. !SDL_ReadU16LE(src, &biBitCount)) {
  243. goto done;
  244. }
  245. biWidth = biWidth16;
  246. biHeight = biHeight16;
  247. biCompression = BI_RGB;
  248. // biSizeImage = 0;
  249. // biXPelsPerMeter = 0;
  250. // biYPelsPerMeter = 0;
  251. biClrUsed = 0;
  252. // biClrImportant = 0;
  253. } else if (biSize >= 40) { // some version of BITMAPINFOHEADER
  254. Uint32 headerSize;
  255. if (!SDL_ReadS32LE(src, &biWidth) ||
  256. !SDL_ReadS32LE(src, &biHeight) ||
  257. !SDL_ReadU16LE(src, NULL /* biPlanes */) ||
  258. !SDL_ReadU16LE(src, &biBitCount) ||
  259. !SDL_ReadU32LE(src, &biCompression) ||
  260. !SDL_ReadU32LE(src, NULL /* biSizeImage */) ||
  261. !SDL_ReadU32LE(src, NULL /* biXPelsPerMeter */) ||
  262. !SDL_ReadU32LE(src, NULL /* biYPelsPerMeter */) ||
  263. !SDL_ReadU32LE(src, &biClrUsed) ||
  264. !SDL_ReadU32LE(src, NULL /* biClrImportant */)) {
  265. goto done;
  266. }
  267. // 64 == BITMAPCOREHEADER2, an incompatible OS/2 2.x extension. Skip this stuff for now.
  268. if (biSize != 64) {
  269. /* This is complicated. If compression is BI_BITFIELDS, then
  270. we have 3 DWORDS that specify the RGB masks. This is either
  271. stored here in an BITMAPV2INFOHEADER (which only differs in
  272. that it adds these RGB masks) and biSize >= 52, or we've got
  273. these masks stored in the exact same place, but strictly
  274. speaking, this is the bmiColors field in BITMAPINFO immediately
  275. following the legacy v1 info header, just past biSize. */
  276. if (biCompression == BI_BITFIELDS) {
  277. haveRGBMasks = true;
  278. if (!SDL_ReadU32LE(src, &Rmask) ||
  279. !SDL_ReadU32LE(src, &Gmask) ||
  280. !SDL_ReadU32LE(src, &Bmask)) {
  281. goto done;
  282. }
  283. // ...v3 adds an alpha mask.
  284. if (biSize >= 56) { // BITMAPV3INFOHEADER; adds alpha mask
  285. haveAlphaMask = true;
  286. if (!SDL_ReadU32LE(src, &Amask)) {
  287. goto done;
  288. }
  289. }
  290. } else {
  291. // the mask fields are ignored for v2+ headers if not BI_BITFIELD.
  292. if (biSize >= 52) { // BITMAPV2INFOHEADER; adds RGB masks
  293. if (!SDL_ReadU32LE(src, NULL /* Rmask */) ||
  294. !SDL_ReadU32LE(src, NULL /* Gmask */) ||
  295. !SDL_ReadU32LE(src, NULL /* Bmask */)) {
  296. goto done;
  297. }
  298. }
  299. if (biSize >= 56) { // BITMAPV3INFOHEADER; adds alpha mask
  300. if (!SDL_ReadU32LE(src, NULL /* Amask */)) {
  301. goto done;
  302. }
  303. }
  304. }
  305. /* Insert other fields here; Wikipedia and MSDN say we're up to
  306. v5 of this header, but we ignore those for now (they add gamma,
  307. color spaces, etc). Ignoring the weird OS/2 2.x format, we
  308. currently parse up to v3 correctly (hopefully!). */
  309. }
  310. // skip any header bytes we didn't handle...
  311. headerSize = (Uint32)(SDL_TellIO(src) - (fp_offset + 14));
  312. if (biSize > headerSize) {
  313. if (SDL_SeekIO(src, (biSize - headerSize), SDL_IO_SEEK_CUR) < 0) {
  314. goto done;
  315. }
  316. }
  317. }
  318. if (biWidth <= 0 || biHeight == 0) {
  319. SDL_SetError("BMP file with bad dimensions (%" SDL_PRIs32 "x%" SDL_PRIs32 ")", biWidth, biHeight);
  320. goto done;
  321. }
  322. if (biHeight < 0) {
  323. topDown = true;
  324. biHeight = -biHeight;
  325. } else {
  326. topDown = false;
  327. }
  328. // Check for read error
  329. if (SDL_strcmp(SDL_GetError(), "") != 0) {
  330. goto done;
  331. }
  332. // Reject invalid bit depths
  333. switch (biBitCount) {
  334. case 0:
  335. case 3:
  336. case 5:
  337. case 6:
  338. case 7:
  339. SDL_SetError("%u bpp BMP images are not supported", biBitCount);
  340. goto done;
  341. default:
  342. break;
  343. }
  344. // RLE4 and RLE8 BMP compression is supported
  345. switch (biCompression) {
  346. case BI_RGB:
  347. // If there are no masks, use the defaults
  348. SDL_assert(!haveRGBMasks);
  349. SDL_assert(!haveAlphaMask);
  350. // Default values for the BMP format
  351. switch (biBitCount) {
  352. case 15:
  353. case 16:
  354. // SDL_PIXELFORMAT_XRGB1555 or SDL_PIXELFORMAT_ARGB1555 if Amask
  355. Rmask = 0x7C00;
  356. Gmask = 0x03E0;
  357. Bmask = 0x001F;
  358. break;
  359. case 24:
  360. #if SDL_BYTEORDER == SDL_BIG_ENDIAN
  361. // SDL_PIXELFORMAT_RGB24
  362. Rmask = 0x000000FF;
  363. Gmask = 0x0000FF00;
  364. Bmask = 0x00FF0000;
  365. #else
  366. // SDL_PIXELFORMAT_BGR24
  367. Rmask = 0x00FF0000;
  368. Gmask = 0x0000FF00;
  369. Bmask = 0x000000FF;
  370. #endif
  371. break;
  372. case 32:
  373. // We don't know if this has alpha channel or not
  374. correctAlpha = true;
  375. // SDL_PIXELFORMAT_RGBA8888
  376. Amask = 0xFF000000;
  377. Rmask = 0x00FF0000;
  378. Gmask = 0x0000FF00;
  379. Bmask = 0x000000FF;
  380. break;
  381. default:
  382. break;
  383. }
  384. break;
  385. case BI_BITFIELDS:
  386. break; // we handled this in the info header.
  387. default:
  388. break;
  389. }
  390. // Create a compatible surface, note that the colors are RGB ordered
  391. {
  392. SDL_PixelFormat format;
  393. // Get the pixel format
  394. format = SDL_GetPixelFormatForMasks(biBitCount, Rmask, Gmask, Bmask, Amask);
  395. surface = SDL_CreateSurface(biWidth, biHeight, format);
  396. if (!surface) {
  397. goto done;
  398. }
  399. }
  400. // Load the palette, if any
  401. if (SDL_ISPIXELFORMAT_INDEXED(surface->format)) {
  402. SDL_Palette *palette = SDL_CreateSurfacePalette(surface);
  403. if (!palette) {
  404. goto done;
  405. }
  406. if (SDL_SeekIO(src, fp_offset + 14 + biSize, SDL_IO_SEEK_SET) < 0) {
  407. SDL_SetError("Error seeking in datastream");
  408. goto done;
  409. }
  410. if (biBitCount >= 32) { // we shift biClrUsed by this value later.
  411. SDL_SetError("Unsupported or incorrect biBitCount field");
  412. goto done;
  413. }
  414. if (biClrUsed == 0) {
  415. biClrUsed = 1 << biBitCount;
  416. }
  417. if (biClrUsed > (Uint32)palette->ncolors) {
  418. biClrUsed = 1 << biBitCount; // try forcing it?
  419. if (biClrUsed > (Uint32)palette->ncolors) {
  420. SDL_SetError("Unsupported or incorrect biClrUsed field");
  421. goto done;
  422. }
  423. }
  424. palette->ncolors = biClrUsed;
  425. if (biSize == 12) {
  426. for (i = 0; i < palette->ncolors; ++i) {
  427. if (!SDL_ReadU8(src, &palette->colors[i].b) ||
  428. !SDL_ReadU8(src, &palette->colors[i].g) ||
  429. !SDL_ReadU8(src, &palette->colors[i].r)) {
  430. goto done;
  431. }
  432. palette->colors[i].a = SDL_ALPHA_OPAQUE;
  433. }
  434. } else {
  435. for (i = 0; i < palette->ncolors; ++i) {
  436. if (!SDL_ReadU8(src, &palette->colors[i].b) ||
  437. !SDL_ReadU8(src, &palette->colors[i].g) ||
  438. !SDL_ReadU8(src, &palette->colors[i].r) ||
  439. !SDL_ReadU8(src, &palette->colors[i].a)) {
  440. goto done;
  441. }
  442. /* According to Microsoft documentation, the fourth element
  443. is reserved and must be zero, so we shouldn't treat it as
  444. alpha.
  445. */
  446. palette->colors[i].a = SDL_ALPHA_OPAQUE;
  447. }
  448. }
  449. }
  450. // Read the surface pixels. Note that the bmp image is upside down
  451. if (SDL_SeekIO(src, fp_offset + bfOffBits, SDL_IO_SEEK_SET) < 0) {
  452. SDL_SetError("Error seeking in datastream");
  453. goto done;
  454. }
  455. if ((biCompression == BI_RLE4) || (biCompression == BI_RLE8)) {
  456. if (!readRlePixels(surface, src, biCompression == BI_RLE8)) {
  457. SDL_SetError("Error reading from datastream");
  458. goto done;
  459. }
  460. // Success!
  461. was_error = false;
  462. goto done;
  463. }
  464. top = (Uint8 *)surface->pixels;
  465. end = (Uint8 *)surface->pixels + (surface->h * surface->pitch);
  466. pad = ((surface->pitch % 4) ? (4 - (surface->pitch % 4)) : 0);
  467. if (topDown) {
  468. bits = top;
  469. } else {
  470. bits = end - surface->pitch;
  471. }
  472. while (bits >= top && bits < end) {
  473. if (SDL_ReadIO(src, bits, surface->pitch) != (size_t)surface->pitch) {
  474. goto done;
  475. }
  476. if (biBitCount == 8 && surface->palette && biClrUsed < (1u << biBitCount)) {
  477. for (i = 0; i < surface->w; ++i) {
  478. if (bits[i] >= biClrUsed) {
  479. SDL_SetError("A BMP image contains a pixel with a color out of the palette");
  480. goto done;
  481. }
  482. }
  483. }
  484. #if SDL_BYTEORDER == SDL_BIG_ENDIAN
  485. /* Byte-swap the pixels if needed. Note that the 24bpp
  486. case has already been taken care of above. */
  487. switch (biBitCount) {
  488. case 15:
  489. case 16:
  490. {
  491. Uint16 *pix = (Uint16 *)bits;
  492. for (i = 0; i < surface->w; i++) {
  493. pix[i] = SDL_Swap16(pix[i]);
  494. }
  495. break;
  496. }
  497. case 32:
  498. {
  499. Uint32 *pix = (Uint32 *)bits;
  500. for (i = 0; i < surface->w; i++) {
  501. pix[i] = SDL_Swap32(pix[i]);
  502. }
  503. break;
  504. }
  505. }
  506. #endif
  507. // Skip padding bytes, ugh
  508. if (pad) {
  509. Uint8 padbyte;
  510. for (i = 0; i < pad; ++i) {
  511. if (!SDL_ReadU8(src, &padbyte)) {
  512. goto done;
  513. }
  514. }
  515. }
  516. if (topDown) {
  517. bits += surface->pitch;
  518. } else {
  519. bits -= surface->pitch;
  520. }
  521. }
  522. if (correctAlpha) {
  523. CorrectAlphaChannel(surface);
  524. }
  525. was_error = false;
  526. done:
  527. if (was_error) {
  528. if (src) {
  529. SDL_SeekIO(src, fp_offset, SDL_IO_SEEK_SET);
  530. }
  531. SDL_DestroySurface(surface);
  532. surface = NULL;
  533. }
  534. if (closeio && src) {
  535. SDL_CloseIO(src);
  536. }
  537. return surface;
  538. }
  539. typedef struct {
  540. SDL_Surface *surface;
  541. SDL_Surface *intermediate_surface;
  542. bool save32bit;
  543. bool saveLegacyBMP;
  544. } BMPSaveState;
  545. static void FreeBMPSaveState(BMPSaveState *state)
  546. {
  547. if (state->intermediate_surface && state->intermediate_surface != state->surface) {
  548. SDL_DestroySurface(state->intermediate_surface);
  549. }
  550. }
  551. static bool InitBMPSaveState(BMPSaveState *state, SDL_Surface *surface)
  552. {
  553. state->surface = surface;
  554. state->intermediate_surface = NULL;
  555. state->save32bit = false;
  556. state->saveLegacyBMP = false;
  557. CHECK_PARAM(!SDL_SurfaceValid(surface)) {
  558. return SDL_InvalidParamError("surface");
  559. }
  560. #ifdef SAVE_32BIT_BMP
  561. // We can save alpha information in a 32-bit BMP
  562. if (SDL_BITSPERPIXEL(surface->format) >= 8 &&
  563. (SDL_ISPIXELFORMAT_ALPHA(surface->format) ||
  564. (surface->map.info.flags & SDL_COPY_COLORKEY))) {
  565. state->save32bit = true;
  566. }
  567. #endif // SAVE_32BIT_BMP
  568. if (surface->palette && !state->save32bit) {
  569. if (SDL_BITSPERPIXEL(surface->format) == 8) {
  570. state->intermediate_surface = surface;
  571. } else {
  572. SDL_SetError("%u bpp BMP files not supported",
  573. SDL_BITSPERPIXEL(surface->format));
  574. goto error;
  575. }
  576. } else if ((surface->format == SDL_PIXELFORMAT_BGR24 && !state->save32bit) ||
  577. (surface->format == SDL_PIXELFORMAT_BGRA32 && state->save32bit)) {
  578. state->intermediate_surface = surface;
  579. } else {
  580. SDL_PixelFormat pixel_format;
  581. /* If the surface has a colorkey or alpha channel we'll save a
  582. 32-bit BMP with alpha channel, otherwise save a 24-bit BMP. */
  583. if (state->save32bit) {
  584. pixel_format = SDL_PIXELFORMAT_BGRA32;
  585. } else {
  586. pixel_format = SDL_PIXELFORMAT_BGR24;
  587. }
  588. state->intermediate_surface = SDL_ConvertSurface(surface, pixel_format);
  589. if (!state->intermediate_surface) {
  590. SDL_SetError("Couldn't convert image to %d bpp",
  591. (int)SDL_BITSPERPIXEL(pixel_format));
  592. goto error;
  593. }
  594. }
  595. if (state->save32bit) {
  596. state->saveLegacyBMP = SDL_GetHintBoolean(SDL_HINT_BMP_SAVE_LEGACY_FORMAT, false);
  597. }
  598. return true;
  599. error:
  600. FreeBMPSaveState(state);
  601. return false;
  602. }
  603. SDL_Surface *SDL_LoadBMP(const char *file)
  604. {
  605. SDL_IOStream *stream = SDL_IOFromFile(file, "rb");
  606. if (!stream) {
  607. return NULL;
  608. }
  609. return SDL_LoadBMP_IO(stream, true);
  610. }
  611. static bool SDL_SaveBMP_IO_Internal(BMPSaveState *state, SDL_IOStream *dst, bool closeio)
  612. {
  613. bool was_error = true;
  614. Sint64 fp_offset, new_offset;
  615. int i, pad;
  616. Uint8 *bits;
  617. // The Win32 BMP file header (14 bytes)
  618. char magic[2] = { 'B', 'M' };
  619. Uint32 bfSize;
  620. Uint16 bfReserved1;
  621. Uint16 bfReserved2;
  622. Uint32 bfOffBits;
  623. // The Win32 BITMAPINFOHEADER struct (40 bytes)
  624. Uint32 biSize;
  625. Sint32 biWidth;
  626. Sint32 biHeight;
  627. Uint16 biPlanes;
  628. Uint16 biBitCount;
  629. Uint32 biCompression;
  630. Uint32 biSizeImage;
  631. Sint32 biXPelsPerMeter;
  632. Sint32 biYPelsPerMeter;
  633. Uint32 biClrUsed;
  634. Uint32 biClrImportant;
  635. // The additional header members from the Win32 BITMAPV4HEADER struct (108 bytes in total)
  636. Uint32 bV4RedMask = 0;
  637. Uint32 bV4GreenMask = 0;
  638. Uint32 bV4BlueMask = 0;
  639. Uint32 bV4AlphaMask = 0;
  640. Uint32 bV4CSType = 0;
  641. Sint32 bV4Endpoints[3 * 3] = { 0 };
  642. Uint32 bV4GammaRed = 0;
  643. Uint32 bV4GammaGreen = 0;
  644. Uint32 bV4GammaBlue = 0;
  645. // The additional header members from the Win32 BITMAPV5HEADER struct (124 bytes in total)
  646. Uint32 bV5Intent = 0;
  647. Uint32 bV5ProfileData = 0;
  648. Uint32 bV5ProfileSize = 0;
  649. Uint32 bV5Reserved = 0;
  650. if (SDL_LockSurface(state->intermediate_surface)) {
  651. const size_t bw = state->intermediate_surface->w * state->intermediate_surface->fmt->bytes_per_pixel;
  652. // Set the BMP file header values
  653. bfSize = 0; // We'll write this when we're done
  654. bfReserved1 = 0;
  655. bfReserved2 = 0;
  656. bfOffBits = 0; // We'll write this when we're done
  657. // Write the BMP file header values
  658. fp_offset = SDL_TellIO(dst);
  659. if (fp_offset < 0) {
  660. goto done;
  661. }
  662. if (SDL_WriteIO(dst, magic, 2) != 2 ||
  663. !SDL_WriteU32LE(dst, bfSize) ||
  664. !SDL_WriteU16LE(dst, bfReserved1) ||
  665. !SDL_WriteU16LE(dst, bfReserved2) ||
  666. !SDL_WriteU32LE(dst, bfOffBits)) {
  667. goto done;
  668. }
  669. // Set the BMP info values
  670. biSize = 40;
  671. biWidth = state->intermediate_surface->w;
  672. biHeight = state->intermediate_surface->h;
  673. biPlanes = 1;
  674. biBitCount = state->intermediate_surface->fmt->bits_per_pixel;
  675. biCompression = BI_RGB;
  676. biSizeImage = state->intermediate_surface->h * state->intermediate_surface->pitch;
  677. biXPelsPerMeter = 0;
  678. biYPelsPerMeter = 0;
  679. if (state->intermediate_surface->palette) {
  680. biClrUsed = state->intermediate_surface->palette->ncolors;
  681. } else {
  682. biClrUsed = 0;
  683. }
  684. biClrImportant = 0;
  685. // Set the BMP info values
  686. if (state->save32bit && !state->saveLegacyBMP) {
  687. biSize = 124;
  688. // Version 4 values
  689. biCompression = BI_BITFIELDS;
  690. // The BMP format is always little endian, these masks stay the same
  691. bV4RedMask = 0x00ff0000;
  692. bV4GreenMask = 0x0000ff00;
  693. bV4BlueMask = 0x000000ff;
  694. bV4AlphaMask = 0xff000000;
  695. bV4CSType = LCS_sRGB;
  696. bV4GammaRed = 0;
  697. bV4GammaGreen = 0;
  698. bV4GammaBlue = 0;
  699. // Version 5 values
  700. bV5Intent = LCS_GM_GRAPHICS;
  701. bV5ProfileData = 0;
  702. bV5ProfileSize = 0;
  703. bV5Reserved = 0;
  704. }
  705. // Write the BMP info values
  706. if (!SDL_WriteU32LE(dst, biSize) ||
  707. !SDL_WriteS32LE(dst, biWidth) ||
  708. !SDL_WriteS32LE(dst, biHeight) ||
  709. !SDL_WriteU16LE(dst, biPlanes) ||
  710. !SDL_WriteU16LE(dst, biBitCount) ||
  711. !SDL_WriteU32LE(dst, biCompression) ||
  712. !SDL_WriteU32LE(dst, biSizeImage) ||
  713. !SDL_WriteU32LE(dst, biXPelsPerMeter) ||
  714. !SDL_WriteU32LE(dst, biYPelsPerMeter) ||
  715. !SDL_WriteU32LE(dst, biClrUsed) ||
  716. !SDL_WriteU32LE(dst, biClrImportant)) {
  717. goto done;
  718. }
  719. // Write the BMP info values
  720. if (state->save32bit && !state->saveLegacyBMP) {
  721. // Version 4 values
  722. if (!SDL_WriteU32LE(dst, bV4RedMask) ||
  723. !SDL_WriteU32LE(dst, bV4GreenMask) ||
  724. !SDL_WriteU32LE(dst, bV4BlueMask) ||
  725. !SDL_WriteU32LE(dst, bV4AlphaMask) ||
  726. !SDL_WriteU32LE(dst, bV4CSType)) {
  727. goto done;
  728. }
  729. for (i = 0; i < 3 * 3; i++) {
  730. if (!SDL_WriteU32LE(dst, bV4Endpoints[i])) {
  731. goto done;
  732. }
  733. }
  734. if (!SDL_WriteU32LE(dst, bV4GammaRed) ||
  735. !SDL_WriteU32LE(dst, bV4GammaGreen) ||
  736. !SDL_WriteU32LE(dst, bV4GammaBlue)) {
  737. goto done;
  738. }
  739. // Version 5 values
  740. if (!SDL_WriteU32LE(dst, bV5Intent) ||
  741. !SDL_WriteU32LE(dst, bV5ProfileData) ||
  742. !SDL_WriteU32LE(dst, bV5ProfileSize) ||
  743. !SDL_WriteU32LE(dst, bV5Reserved)) {
  744. goto done;
  745. }
  746. }
  747. // Write the palette (in BGR color order)
  748. if (state->intermediate_surface->palette) {
  749. SDL_Color *colors;
  750. int ncolors;
  751. colors = state->intermediate_surface->palette->colors;
  752. ncolors = state->intermediate_surface->palette->ncolors;
  753. for (i = 0; i < ncolors; ++i) {
  754. if (!SDL_WriteU8(dst, colors[i].b) ||
  755. !SDL_WriteU8(dst, colors[i].g) ||
  756. !SDL_WriteU8(dst, colors[i].r) ||
  757. !SDL_WriteU8(dst, colors[i].a)) {
  758. goto done;
  759. }
  760. }
  761. }
  762. // Write the bitmap offset
  763. bfOffBits = (Uint32)(SDL_TellIO(dst) - fp_offset);
  764. if (SDL_SeekIO(dst, fp_offset + 10, SDL_IO_SEEK_SET) < 0) {
  765. goto done;
  766. }
  767. if (!SDL_WriteU32LE(dst, bfOffBits)) {
  768. goto done;
  769. }
  770. if (SDL_SeekIO(dst, fp_offset + bfOffBits, SDL_IO_SEEK_SET) < 0) {
  771. goto done;
  772. }
  773. // Write the bitmap image upside down
  774. bits = (Uint8 *)state->intermediate_surface->pixels + (state->intermediate_surface->h * state->intermediate_surface->pitch);
  775. pad = ((bw % 4) ? (4 - (bw % 4)) : 0);
  776. while (bits > (Uint8 *)state->intermediate_surface->pixels) {
  777. bits -= state->intermediate_surface->pitch;
  778. if (SDL_WriteIO(dst, bits, bw) != bw) {
  779. goto done;
  780. }
  781. if (pad) {
  782. const Uint8 padbyte = 0;
  783. for (i = 0; i < pad; ++i) {
  784. if (!SDL_WriteU8(dst, padbyte)) {
  785. goto done;
  786. }
  787. }
  788. }
  789. }
  790. // Write the BMP file size
  791. new_offset = SDL_TellIO(dst);
  792. if (new_offset < 0) {
  793. goto done;
  794. }
  795. bfSize = (Uint32)(new_offset - fp_offset);
  796. if (SDL_SeekIO(dst, fp_offset + 2, SDL_IO_SEEK_SET) < 0) {
  797. goto done;
  798. }
  799. if (!SDL_WriteU32LE(dst, bfSize)) {
  800. goto done;
  801. }
  802. if (SDL_SeekIO(dst, fp_offset + bfSize, SDL_IO_SEEK_SET) < 0) {
  803. goto done;
  804. }
  805. // Close it up..
  806. SDL_UnlockSurface(state->intermediate_surface);
  807. was_error = false;
  808. }
  809. done:
  810. if (closeio && dst) {
  811. if (!SDL_CloseIO(dst)) {
  812. was_error = true;
  813. }
  814. }
  815. if (was_error) {
  816. return false;
  817. }
  818. return true;
  819. }
  820. bool SDL_SaveBMP_IO(SDL_Surface *surface, SDL_IOStream *dst, bool closeio)
  821. {
  822. bool result = true;
  823. BMPSaveState state;
  824. if (!InitBMPSaveState(&state, surface)) {
  825. return false;
  826. }
  827. CHECK_PARAM(!dst) {
  828. result = SDL_InvalidParamError("dst");
  829. goto done;
  830. }
  831. result = SDL_SaveBMP_IO_Internal(&state, dst, closeio);
  832. done:
  833. FreeBMPSaveState(&state);
  834. return result;
  835. }
  836. bool SDL_SaveBMP(SDL_Surface *surface, const char *file)
  837. {
  838. BMPSaveState state;
  839. if (!InitBMPSaveState(&state, surface)) {
  840. return false;
  841. }
  842. SDL_IOStream *stream = SDL_IOFromFile(file, "wb");
  843. if (!stream) {
  844. return false;
  845. }
  846. bool result = SDL_SaveBMP_IO_Internal(&state, stream, true);
  847. FreeBMPSaveState(&state);
  848. return result;
  849. }