SDL_bmp.c 28 KB

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