stb_image_write.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. #include "stb_image_write.h"
  2. #include <stdarg.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <assert.h>
  7. typedef unsigned int stbiw_uint32;
  8. typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1];
  9. static void writefv(FILE *f, const char *fmt, va_list v)
  10. {
  11. while (*fmt) {
  12. switch (*fmt++) {
  13. case ' ': break;
  14. case '1': { unsigned char x = (unsigned char) va_arg(v, int); fputc(x,f); break; }
  15. case '2': { int x = va_arg(v,int); unsigned char b[2];
  16. b[0] = (unsigned char) x; b[1] = (unsigned char) (x>>8);
  17. fwrite(b,2,1,f); break; }
  18. case '4': { stbiw_uint32 x = va_arg(v,int); unsigned char b[4];
  19. b[0]=(unsigned char)x; b[1]=(unsigned char)(x>>8);
  20. b[2]=(unsigned char)(x>>16); b[3]=(unsigned char)(x>>24);
  21. fwrite(b,4,1,f); break; }
  22. default:
  23. assert(0);
  24. return;
  25. }
  26. }
  27. }
  28. static void write3(FILE *f, unsigned char a, unsigned char b, unsigned char c)
  29. {
  30. unsigned char arr[3];
  31. arr[0] = a, arr[1] = b, arr[2] = c;
  32. fwrite(arr, 3, 1, f);
  33. }
  34. static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad)
  35. {
  36. unsigned char bg[3] = { 255, 0, 255}, px[3];
  37. stbiw_uint32 zero = 0;
  38. int i,j,k, j_end;
  39. if (y <= 0)
  40. return;
  41. if (vdir < 0)
  42. j_end = -1, j = y-1;
  43. else
  44. j_end = y, j = 0;
  45. for (; j != j_end; j += vdir) {
  46. for (i=0; i < x; ++i) {
  47. unsigned char *d = (unsigned char *) data + (j*x+i)*comp;
  48. if (write_alpha < 0)
  49. fwrite(&d[comp-1], 1, 1, f);
  50. switch (comp) {
  51. case 1:
  52. case 2: write3(f, d[0],d[0],d[0]);
  53. break;
  54. case 4:
  55. if (!write_alpha) {
  56. // composite against pink background
  57. for (k=0; k < 3; ++k)
  58. px[k] = bg[k] + ((d[k] - bg[k]) * d[3])/255;
  59. write3(f, px[1-rgb_dir],px[1],px[1+rgb_dir]);
  60. break;
  61. }
  62. /* FALLTHROUGH */
  63. case 3:
  64. write3(f, d[1-rgb_dir],d[1],d[1+rgb_dir]);
  65. break;
  66. }
  67. if (write_alpha > 0)
  68. fwrite(&d[comp-1], 1, 1, f);
  69. }
  70. fwrite(&zero,scanline_pad,1,f);
  71. }
  72. }
  73. static int outfile(char const *filename, int rgb_dir, int vdir, int x, int y, int comp, void *data, int alpha, int pad, const char *fmt, ...)
  74. {
  75. FILE *f;
  76. if (y < 0 || x < 0) return 0;
  77. f = fopen(filename, "wb");
  78. if (f) {
  79. va_list v;
  80. va_start(v, fmt);
  81. writefv(f, fmt, v);
  82. va_end(v);
  83. write_pixels(f,rgb_dir,vdir,x,y,comp,data,alpha,pad);
  84. fclose(f);
  85. }
  86. return f != NULL;
  87. }
  88. int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data)
  89. {
  90. int pad = (-x*3) & 3;
  91. return outfile(filename,-1,-1,x,y,comp,(void *) data,0,pad,
  92. "11 4 22 4" "4 44 22 444444",
  93. 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header
  94. 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header
  95. }
  96. int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data)
  97. {
  98. int has_alpha = !(comp & 1);
  99. return outfile(filename, -1,-1, x, y, comp, (void *) data, has_alpha, 0,
  100. "111 221 2222 11", 0,0,2, 0,0,0, 0,0,x,y, 24+8*has_alpha, 8*has_alpha);
  101. }
  102. // stretchy buffer; stbi__sbpush() == vector<>::push_back() -- stbi__sbcount() == vector<>::size()
  103. #define stbi__sbraw(a) ((int *) (a) - 2)
  104. #define stbi__sbm(a) stbi__sbraw(a)[0]
  105. #define stbi__sbn(a) stbi__sbraw(a)[1]
  106. #define stbi__sbneedgrow(a,n) ((a)==0 || stbi__sbn(a)+n >= stbi__sbm(a))
  107. #define stbi__sbmaybegrow(a,n) (stbi__sbneedgrow(a,(n)) ? stbi__sbgrow(a,n) : 0)
  108. #define stbi__sbgrow(a,n) stbi__sbgrowf((void **) &(a), (n), sizeof(*(a)))
  109. #define stbi__sbpush(a, v) (stbi__sbmaybegrow(a,1), (a)[stbi__sbn(a)++] = (v))
  110. #define stbi__sbcount(a) ((a) ? stbi__sbn(a) : 0)
  111. #define stbi__sbfree(a) ((a) ? free(stbi__sbraw(a)),0 : 0)
  112. static void *stbi__sbgrowf(void **arr, int increment, int itemsize)
  113. {
  114. int m = *arr ? 2*stbi__sbm(*arr)+increment : increment+1;
  115. void *p = realloc(*arr ? stbi__sbraw(*arr) : 0, itemsize * m + sizeof(int)*2);
  116. assert(p);
  117. if (p) {
  118. if (!*arr) ((int *) p)[1] = 0;
  119. *arr = (void *) ((int *) p + 2);
  120. stbi__sbm(*arr) = m;
  121. }
  122. return *arr;
  123. }
  124. static unsigned char *stbi__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount)
  125. {
  126. while (*bitcount >= 8) {
  127. stbi__sbpush(data, (unsigned char) *bitbuffer);
  128. *bitbuffer >>= 8;
  129. *bitcount -= 8;
  130. }
  131. return data;
  132. }
  133. static int stbi__zlib_bitrev(int code, int codebits)
  134. {
  135. int res=0;
  136. while (codebits--) {
  137. res = (res << 1) | (code & 1);
  138. code >>= 1;
  139. }
  140. return res;
  141. }
  142. static unsigned int stbi__zlib_countm(unsigned char *a, unsigned char *b, int limit)
  143. {
  144. int i;
  145. for (i=0; i < limit && i < 258; ++i)
  146. if (a[i] != b[i]) break;
  147. return i;
  148. }
  149. static unsigned int stbi__zhash(unsigned char *data)
  150. {
  151. stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16);
  152. hash ^= hash << 3;
  153. hash += hash >> 5;
  154. hash ^= hash << 4;
  155. hash += hash >> 17;
  156. hash ^= hash << 25;
  157. hash += hash >> 6;
  158. return hash;
  159. }
  160. #define stbi__zlib_flush() (out = stbi__zlib_flushf(out, &bitbuf, &bitcount))
  161. #define stbi__zlib_add(code,codebits) \
  162. (bitbuf |= (code) << bitcount, bitcount += (codebits), stbi__zlib_flush())
  163. #define stbi__zlib_huffa(b,c) stbi__zlib_add(stbi__zlib_bitrev(b,c),c)
  164. // default huffman tables
  165. #define stbi__zlib_huff1(n) stbi__zlib_huffa(0x30 + (n), 8)
  166. #define stbi__zlib_huff2(n) stbi__zlib_huffa(0x190 + (n)-144, 9)
  167. #define stbi__zlib_huff3(n) stbi__zlib_huffa(0 + (n)-256,7)
  168. #define stbi__zlib_huff4(n) stbi__zlib_huffa(0xc0 + (n)-280,8)
  169. #define stbi__zlib_huff(n) ((n) <= 143 ? stbi__zlib_huff1(n) : (n) <= 255 ? stbi__zlib_huff2(n) : (n) <= 279 ? stbi__zlib_huff3(n) : stbi__zlib_huff4(n))
  170. #define stbi__zlib_huffb(n) ((n) <= 143 ? stbi__zlib_huff1(n) : stbi__zlib_huff2(n))
  171. #define stbi__ZHASH 16384
  172. unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality)
  173. {
  174. static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 };
  175. static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 };
  176. static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 };
  177. static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 };
  178. unsigned int bitbuf=0;
  179. int i,j, bitcount=0;
  180. unsigned char *out = NULL;
  181. unsigned char **hash_table[stbi__ZHASH]; // 64KB on the stack!
  182. if (quality < 5) quality = 5;
  183. stbi__sbpush(out, 0x78); // DEFLATE 32K window
  184. stbi__sbpush(out, 0x5e); // FLEVEL = 1
  185. stbi__zlib_add(1,1); // BFINAL = 1
  186. stbi__zlib_add(1,2); // BTYPE = 1 -- fixed huffman
  187. for (i=0; i < stbi__ZHASH; ++i)
  188. hash_table[i] = NULL;
  189. i=0;
  190. while (i < data_len-3) {
  191. // hash next 3 bytes of data to be compressed
  192. int h = stbi__zhash(data+i)&(stbi__ZHASH-1), best=3;
  193. unsigned char *bestloc = 0;
  194. unsigned char **hlist = hash_table[h];
  195. int n = stbi__sbcount(hlist);
  196. for (j=0; j < n; ++j) {
  197. if (hlist[j]-data > i-32768) { // if entry lies within window
  198. int d = stbi__zlib_countm(hlist[j], data+i, data_len-i);
  199. if (d >= best) best=d,bestloc=hlist[j];
  200. }
  201. }
  202. // when hash table entry is too long, delete half the entries
  203. if (hash_table[h] && stbi__sbn(hash_table[h]) == 2*quality) {
  204. memcpy(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality);
  205. stbi__sbn(hash_table[h]) = quality;
  206. }
  207. stbi__sbpush(hash_table[h],data+i);
  208. if (bestloc) {
  209. // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal
  210. h = stbi__zhash(data+i+1)&(stbi__ZHASH-1);
  211. hlist = hash_table[h];
  212. n = stbi__sbcount(hlist);
  213. for (j=0; j < n; ++j) {
  214. if (hlist[j]-data > i-32767) {
  215. int e = stbi__zlib_countm(hlist[j], data+i+1, data_len-i-1);
  216. if (e > best) { // if next match is better, bail on current match
  217. bestloc = NULL;
  218. break;
  219. }
  220. }
  221. }
  222. }
  223. if (bestloc) {
  224. int d = data+i - bestloc; // distance back
  225. assert(d <= 32767 && best <= 258);
  226. for (j=0; best > lengthc[j+1]-1; ++j);
  227. stbi__zlib_huff(j+257);
  228. if (lengtheb[j]) stbi__zlib_add(best - lengthc[j], lengtheb[j]);
  229. for (j=0; d > distc[j+1]-1; ++j);
  230. stbi__zlib_add(stbi__zlib_bitrev(j,5),5);
  231. if (disteb[j]) stbi__zlib_add(d - distc[j], disteb[j]);
  232. i += best;
  233. } else {
  234. stbi__zlib_huffb(data[i]);
  235. ++i;
  236. }
  237. }
  238. // write out final bytes
  239. for (;i < data_len; ++i)
  240. stbi__zlib_huffb(data[i]);
  241. stbi__zlib_huff(256); // end of block
  242. // pad with 0 bits to byte boundary
  243. while (bitcount)
  244. stbi__zlib_add(0,1);
  245. for (i=0; i < stbi__ZHASH; ++i)
  246. (void) stbi__sbfree(hash_table[i]);
  247. {
  248. // compute adler32 on input
  249. unsigned int i=0, s1=1, s2=0, blocklen = data_len % 5552;
  250. int j=0;
  251. while (j < data_len) {
  252. for (i=0; i < blocklen; ++i) s1 += data[j+i], s2 += s1;
  253. s1 %= 65521, s2 %= 65521;
  254. j += blocklen;
  255. blocklen = 5552;
  256. }
  257. stbi__sbpush(out, (unsigned char) (s2 >> 8));
  258. stbi__sbpush(out, (unsigned char) s2);
  259. stbi__sbpush(out, (unsigned char) (s1 >> 8));
  260. stbi__sbpush(out, (unsigned char) s1);
  261. }
  262. *out_len = stbi__sbn(out);
  263. // make returned pointer freeable
  264. memmove(stbi__sbraw(out), out, *out_len);
  265. return (unsigned char *) stbi__sbraw(out);
  266. }
  267. unsigned int stbi__crc32(unsigned char *buffer, int len)
  268. {
  269. static unsigned int crc_table[256];
  270. unsigned int crc = ~0u;
  271. int i,j;
  272. if (crc_table[1] == 0)
  273. for(i=0; i < 256; i++)
  274. for (crc_table[i]=i, j=0; j < 8; ++j)
  275. crc_table[i] = (crc_table[i] >> 1) ^ (crc_table[i] & 1 ? 0xedb88320 : 0);
  276. for (i=0; i < len; ++i)
  277. crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];
  278. return ~crc;
  279. }
  280. #define stbi__wpng4(o,a,b,c,d) ((o)[0]=(unsigned char)(a),(o)[1]=(unsigned char)(b),(o)[2]=(unsigned char)(c),(o)[3]=(unsigned char)(d),(o)+=4)
  281. #define stbi__wp32(data,v) stbi__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v));
  282. #define stbi__wptag(data,s) stbi__wpng4(data, s[0],s[1],s[2],s[3])
  283. static void stbi__wpcrc(unsigned char **data, int len)
  284. {
  285. unsigned int crc = stbi__crc32(*data - len - 4, len+4);
  286. stbi__wp32(*data, crc);
  287. }
  288. static unsigned char stbi__paeth(int a, int b, int c)
  289. {
  290. int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c);
  291. if (pa <= pb && pa <= pc) return (unsigned char) a;
  292. if (pb <= pc) return (unsigned char) b;
  293. return (unsigned char) c;
  294. }
  295. unsigned char *stbi_write_png_to_mem(unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len)
  296. {
  297. int ctype[5] = { -1, 0, 4, 2, 6 };
  298. unsigned char sig[8] = { 137,80,78,71,13,10,26,10 };
  299. unsigned char *out,*o, *filt, *zlib;
  300. signed char *line_buffer;
  301. int i,j,k,p,zlen;
  302. if (stride_bytes == 0)
  303. stride_bytes = x * n;
  304. filt = (unsigned char *) malloc((x*n+1) * y); if (!filt) return 0;
  305. line_buffer = (signed char *) malloc(x * n); if (!line_buffer) { free(filt); return 0; }
  306. for (j=0; j < y; ++j) {
  307. static int mapping[] = { 0,1,2,3,4 };
  308. static int firstmap[] = { 0,1,0,5,6 };
  309. int *mymap = j ? mapping : firstmap;
  310. int best = 0, bestval = 0x7fffffff;
  311. for (p=0; p < 2; ++p) {
  312. for (k= p?best:0; k < 5; ++k) {
  313. int type = mymap[k],est=0;
  314. unsigned char *z = pixels + stride_bytes*j;
  315. for (i=0; i < n; ++i)
  316. switch (type) {
  317. case 0: line_buffer[i] = z[i]; break;
  318. case 1: line_buffer[i] = z[i]; break;
  319. case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;
  320. case 3: line_buffer[i] = z[i] - (z[i-stride_bytes]>>1); break;
  321. case 4: line_buffer[i] = (signed char) (z[i] - stbi__paeth(0,z[i-stride_bytes],0)); break;
  322. case 5: line_buffer[i] = z[i]; break;
  323. case 6: line_buffer[i] = z[i]; break;
  324. }
  325. for (i=n; i < x*n; ++i) {
  326. switch (type) {
  327. case 0: line_buffer[i] = z[i]; break;
  328. case 1: line_buffer[i] = z[i] - z[i-n]; break;
  329. case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;
  330. case 3: line_buffer[i] = z[i] - ((z[i-n] + z[i-stride_bytes])>>1); break;
  331. case 4: line_buffer[i] = z[i] - stbi__paeth(z[i-n], z[i-stride_bytes], z[i-stride_bytes-n]); break;
  332. case 5: line_buffer[i] = z[i] - (z[i-n]>>1); break;
  333. case 6: line_buffer[i] = z[i] - stbi__paeth(z[i-n], 0,0); break;
  334. }
  335. }
  336. if (p) break;
  337. for (i=0; i < x*n; ++i)
  338. est += abs((signed char) line_buffer[i]);
  339. if (est < bestval) { bestval = est; best = k; }
  340. }
  341. }
  342. // when we get here, best contains the filter type, and line_buffer contains the data
  343. filt[j*(x*n+1)] = (unsigned char) best;
  344. memcpy(filt+j*(x*n+1)+1, line_buffer, x*n);
  345. }
  346. free(line_buffer);
  347. zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, 8); // increase 8 to get smaller but use more memory
  348. free(filt);
  349. if (!zlib) return 0;
  350. // each tag requires 12 bytes of overhead
  351. out = (unsigned char *) malloc(8 + 12+13 + 12+zlen + 12);
  352. if (!out) return 0;
  353. *out_len = 8 + 12+13 + 12+zlen + 12;
  354. o=out;
  355. memcpy(o,sig,8); o+= 8;
  356. stbi__wp32(o, 13); // header length
  357. stbi__wptag(o, "IHDR");
  358. stbi__wp32(o, x);
  359. stbi__wp32(o, y);
  360. *o++ = 8;
  361. *o++ = (unsigned char) ctype[n];
  362. *o++ = 0;
  363. *o++ = 0;
  364. *o++ = 0;
  365. stbi__wpcrc(&o,13);
  366. stbi__wp32(o, zlen);
  367. stbi__wptag(o, "IDAT");
  368. memcpy(o, zlib, zlen); o += zlen; free(zlib);
  369. stbi__wpcrc(&o, zlen);
  370. stbi__wp32(o,0);
  371. stbi__wptag(o, "IEND");
  372. stbi__wpcrc(&o,0);
  373. assert(o == out + *out_len);
  374. return out;
  375. }
  376. int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes)
  377. {
  378. FILE *f;
  379. int len;
  380. unsigned char *png = stbi_write_png_to_mem((unsigned char *) data, stride_bytes, x, y, comp, &len);
  381. if (!png) return 0;
  382. f = fopen(filename, "wb");
  383. if (!f) { free(png); return 0; }
  384. fwrite(png, 1, len, f);
  385. fclose(f);
  386. free(png);
  387. return 1;
  388. }
  389. /* Revision history
  390. 0.92 (2010-08-01)
  391. casts to unsigned char to fix warnings
  392. 0.91 (2010-07-17)
  393. first public release
  394. 0.90 first internal release
  395. */