wpng.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. /*---------------------------------------------------------------------------
  2. wpng - simple PNG-writing program wpng.c
  3. This program converts certain NetPBM binary files (grayscale and RGB,
  4. maxval = 255) to PNG. Non-interlaced PNGs are written progressively;
  5. interlaced PNGs are read and written in one memory-intensive blast.
  6. Thanks to Jean-loup Gailly for providing the necessary trick to read
  7. interactive text from the keyboard while stdin is redirected. Thanks
  8. to Cosmin Truta for Cygwin fixes.
  9. NOTE: includes provisional support for PNM type "8" (portable alphamap)
  10. images, presumed to be a 32-bit interleaved RGBA format; no pro-
  11. vision for possible interleaved grayscale+alpha (16-bit) format.
  12. THIS IS UNLIKELY TO BECOME AN OFFICIAL NETPBM ALPHA FORMAT!
  13. to do:
  14. - delete output file if quit before calling any writepng routines
  15. - process backspace with -text option under DOS/Win? (currently get ^H)
  16. ---------------------------------------------------------------------------
  17. Changelog:
  18. - 1.01: initial public release
  19. - 1.02: modified to allow abbreviated options
  20. - 1.03: removed extraneous character from usage screen; fixed bug in
  21. command-line parsing
  22. - 1.04: fixed DOS/OS2/Win32 detection, including partial Cygwin fix
  23. (see http://home.att.net/~perlspinr/diffs/GregBook_cygwin.diff)
  24. - 2.00: dual-licensed (added GNU GPL)
  25. [REPORTED BUG (win32 only): "contrib/gregbook/wpng.c - cmd line
  26. dose not work! In order to do something useful I needed to redirect
  27. both input and output, with cygwin and with bcc32 as well. Under
  28. Linux, the same wpng appears to work fine. I don't know what is
  29. the problem."]
  30. ---------------------------------------------------------------------------
  31. Copyright (c) 1998-2007 Greg Roelofs. All rights reserved.
  32. This software is provided "as is," without warranty of any kind,
  33. express or implied. In no event shall the author or contributors
  34. be held liable for any damages arising in any way from the use of
  35. this software.
  36. The contents of this file are DUAL-LICENSED. You may modify and/or
  37. redistribute this software according to the terms of one of the
  38. following two licenses (at your option):
  39. LICENSE 1 ("BSD-like with advertising clause"):
  40. Permission is granted to anyone to use this software for any purpose,
  41. including commercial applications, and to alter it and redistribute
  42. it freely, subject to the following restrictions:
  43. 1. Redistributions of source code must retain the above copyright
  44. notice, disclaimer, and this list of conditions.
  45. 2. Redistributions in binary form must reproduce the above copyright
  46. notice, disclaimer, and this list of conditions in the documenta-
  47. tion and/or other materials provided with the distribution.
  48. 3. All advertising materials mentioning features or use of this
  49. software must display the following acknowledgment:
  50. This product includes software developed by Greg Roelofs
  51. and contributors for the book, "PNG: The Definitive Guide,"
  52. published by O'Reilly and Associates.
  53. LICENSE 2 (GNU GPL v2 or later):
  54. This program is free software; you can redistribute it and/or modify
  55. it under the terms of the GNU General Public License as published by
  56. the Free Software Foundation; either version 2 of the License, or
  57. (at your option) any later version.
  58. This program is distributed in the hope that it will be useful,
  59. but WITHOUT ANY WARRANTY; without even the implied warranty of
  60. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  61. GNU General Public License for more details.
  62. You should have received a copy of the GNU General Public License
  63. along with this program; if not, write to the Free Software Foundation,
  64. Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  65. ---------------------------------------------------------------------------*/
  66. #define PROGNAME "wpng"
  67. #define VERSION "2.00 of 2 June 2007"
  68. #define APPNAME "Simple PGM/PPM/PAM to PNG Converter"
  69. #if defined(__MSDOS__) || defined(__OS2__)
  70. # define DOS_OS2_W32
  71. #elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
  72. # ifndef __GNUC__ /* treat Win32 native ports of gcc as Unix environments */
  73. # define DOS_OS2_W32
  74. # endif
  75. #endif
  76. #include <stdio.h>
  77. #include <stdlib.h>
  78. #include <string.h>
  79. #include <setjmp.h> /* for jmpbuf declaration in writepng.h */
  80. #include <time.h>
  81. #ifdef DOS_OS2_W32
  82. # include <io.h> /* for isatty(), setmode() prototypes */
  83. # include <fcntl.h> /* O_BINARY for fdopen() without text translation */
  84. # ifdef __EMX__
  85. # ifndef getch
  86. # define getch() _read_kbd(0, 1, 0) /* need getche() */
  87. # endif
  88. # else /* !__EMX__ */
  89. # ifdef __GO32__
  90. # include <pc.h>
  91. # define getch() getkey() /* GRR: need getche() */
  92. # else
  93. # include <conio.h> /* for getche() console input */
  94. # endif
  95. # endif /* ?__EMX__ */
  96. # define FGETS(buf,len,stream) dos_kbd_gets(buf,len)
  97. #else
  98. # include <unistd.h> /* for isatty() prototype */
  99. # define FGETS fgets
  100. #endif
  101. /* #define DEBUG : this enables the Trace() macros */
  102. /* #define FORBID_LATIN1_CTRL : this requires the user to re-enter any
  103. text that includes control characters discouraged by the PNG spec; text
  104. that includes an escape character (27) must be re-entered regardless */
  105. #include "writepng.h" /* typedefs, common macros, writepng prototypes */
  106. /* local prototypes */
  107. static int wpng_isvalid_latin1(uch *p, int len);
  108. static void wpng_cleanup(void);
  109. #ifdef DOS_OS2_W32
  110. static char *dos_kbd_gets(char *buf, int len);
  111. #endif
  112. static mainprog_info wpng_info; /* lone global */
  113. int main(int argc, char **argv)
  114. {
  115. #ifndef DOS_OS2_W32
  116. FILE *keybd;
  117. #endif
  118. #ifdef sgi
  119. FILE *tmpfile; /* or we could just use keybd, since no overlap */
  120. char tmpline[80];
  121. #endif
  122. char *inname = NULL, outname[256];
  123. char *p, pnmchar, pnmline[256];
  124. char *bgstr, *textbuf = NULL;
  125. ulg rowbytes;
  126. int rc, len = 0;
  127. int error = 0;
  128. int text = FALSE;
  129. int maxval;
  130. double LUT_exponent; /* just the lookup table */
  131. double CRT_exponent = 2.2; /* just the monitor */
  132. double default_display_exponent; /* whole display system */
  133. double default_gamma = 0.0;
  134. wpng_info.infile = NULL;
  135. wpng_info.outfile = NULL;
  136. wpng_info.image_data = NULL;
  137. wpng_info.row_pointers = NULL;
  138. wpng_info.filter = FALSE;
  139. wpng_info.interlaced = FALSE;
  140. wpng_info.have_bg = FALSE;
  141. wpng_info.have_time = FALSE;
  142. wpng_info.have_text = 0;
  143. wpng_info.gamma = 0.0;
  144. /* First get the default value for our display-system exponent, i.e.,
  145. * the product of the CRT exponent and the exponent corresponding to
  146. * the frame-buffer's lookup table (LUT), if any. If the PNM image
  147. * looks correct on the user's display system, its file gamma is the
  148. * inverse of this value. (Note that this is not an exhaustive list
  149. * of LUT values--e.g., OpenStep has a lot of weird ones--but it should
  150. * cover 99% of the current possibilities. This section must ensure
  151. * that default_display_exponent is positive.) */
  152. #if defined(NeXT)
  153. /* third-party utilities can modify the default LUT exponent */
  154. LUT_exponent = 1.0 / 2.2;
  155. /*
  156. if (some_next_function_that_returns_gamma(&next_gamma))
  157. LUT_exponent = 1.0 / next_gamma;
  158. */
  159. #elif defined(sgi)
  160. LUT_exponent = 1.0 / 1.7;
  161. /* there doesn't seem to be any documented function to
  162. * get the "gamma" value, so we do it the hard way */
  163. tmpfile = fopen("/etc/config/system.glGammaVal", "r");
  164. if (tmpfile) {
  165. double sgi_gamma;
  166. fgets(tmpline, 80, tmpfile);
  167. fclose(tmpfile);
  168. sgi_gamma = atof(tmpline);
  169. if (sgi_gamma > 0.0)
  170. LUT_exponent = 1.0 / sgi_gamma;
  171. }
  172. #elif defined(Macintosh)
  173. LUT_exponent = 1.8 / 2.61;
  174. /*
  175. if (some_mac_function_that_returns_gamma(&mac_gamma))
  176. LUT_exponent = mac_gamma / 2.61;
  177. */
  178. #else
  179. LUT_exponent = 1.0; /* assume no LUT: most PCs */
  180. #endif
  181. /* the defaults above give 1.0, 1.3, 1.5 and 2.2, respectively: */
  182. default_display_exponent = LUT_exponent * CRT_exponent;
  183. /* If the user has set the SCREEN_GAMMA environment variable as suggested
  184. * (somewhat imprecisely) in the libpng documentation, use that; otherwise
  185. * use the default value we just calculated. Either way, the user may
  186. * override this via a command-line option. */
  187. if ((p = getenv("SCREEN_GAMMA")) != NULL) {
  188. double exponent = atof(p);
  189. if (exponent > 0.0)
  190. default_gamma = 1.0 / exponent;
  191. }
  192. if (default_gamma == 0.0)
  193. default_gamma = 1.0 / default_display_exponent;
  194. /* Now parse the command line for options and the PNM filename. */
  195. while (*++argv && !error) {
  196. if (!strncmp(*argv, "-i", 2)) {
  197. wpng_info.interlaced = TRUE;
  198. } else if (!strncmp(*argv, "-time", 3)) {
  199. wpng_info.modtime = time(NULL);
  200. wpng_info.have_time = TRUE;
  201. } else if (!strncmp(*argv, "-text", 3)) {
  202. text = TRUE;
  203. } else if (!strncmp(*argv, "-gamma", 2)) {
  204. if (!*++argv)
  205. ++error;
  206. else {
  207. wpng_info.gamma = atof(*argv);
  208. if (wpng_info.gamma <= 0.0)
  209. ++error;
  210. else if (wpng_info.gamma > 1.01)
  211. fprintf(stderr, PROGNAME
  212. " warning: file gammas are usually less than 1.0\n");
  213. }
  214. } else if (!strncmp(*argv, "-bgcolor", 4)) {
  215. if (!*++argv)
  216. ++error;
  217. else {
  218. bgstr = *argv;
  219. if (strlen(bgstr) != 7 || bgstr[0] != '#')
  220. ++error;
  221. else {
  222. unsigned r, g, b; /* this way quiets compiler warnings */
  223. sscanf(bgstr+1, "%2x%2x%2x", &r, &g, &b);
  224. wpng_info.bg_red = (uch)r;
  225. wpng_info.bg_green = (uch)g;
  226. wpng_info.bg_blue = (uch)b;
  227. wpng_info.have_bg = TRUE;
  228. }
  229. }
  230. } else {
  231. if (**argv != '-') {
  232. inname = *argv;
  233. if (argv[1]) /* shouldn't be any more args after filename */
  234. ++error;
  235. } else
  236. ++error; /* not expecting any other options */
  237. }
  238. }
  239. /* open the input and output files, or register an error and abort */
  240. if (!inname) {
  241. if (isatty(0)) {
  242. fprintf(stderr, PROGNAME
  243. ": must give input filename or provide image data via stdin\n");
  244. ++error;
  245. } else {
  246. #ifdef DOS_OS2_W32
  247. /* some buggy C libraries require BOTH setmode() and fdopen(bin) */
  248. setmode(fileno(stdin), O_BINARY);
  249. setmode(fileno(stdout), O_BINARY);
  250. #endif
  251. if ((wpng_info.infile = fdopen(fileno(stdin), "rb")) == NULL) {
  252. fprintf(stderr, PROGNAME
  253. ": unable to reopen stdin in binary mode\n");
  254. ++error;
  255. } else
  256. if ((wpng_info.outfile = fdopen(fileno(stdout), "wb")) == NULL) {
  257. fprintf(stderr, PROGNAME
  258. ": unable to reopen stdout in binary mode\n");
  259. fclose(wpng_info.infile);
  260. ++error;
  261. } else
  262. wpng_info.filter = TRUE;
  263. }
  264. } else if ((len = strlen(inname)) > 250) {
  265. fprintf(stderr, PROGNAME ": input filename is too long [%d chars]\n",
  266. len);
  267. ++error;
  268. } else if (!(wpng_info.infile = fopen(inname, "rb"))) {
  269. fprintf(stderr, PROGNAME ": can't open input file [%s]\n", inname);
  270. ++error;
  271. }
  272. if (!error) {
  273. fgets(pnmline, 256, wpng_info.infile);
  274. if (pnmline[0] != 'P' || ((pnmchar = pnmline[1]) != '5' &&
  275. pnmchar != '6' && pnmchar != '8'))
  276. {
  277. fprintf(stderr, PROGNAME
  278. ": input file [%s] is not a binary PGM, PPM or PAM file\n",
  279. inname);
  280. ++error;
  281. } else {
  282. wpng_info.pnmtype = (int)(pnmchar - '0');
  283. if (wpng_info.pnmtype != 8)
  284. wpng_info.have_bg = FALSE; /* no need for bg if opaque */
  285. do {
  286. fgets(pnmline, 256, wpng_info.infile); /* lose any comments */
  287. } while (pnmline[0] == '#');
  288. sscanf(pnmline, "%ld %ld", &wpng_info.width, &wpng_info.height);
  289. do {
  290. fgets(pnmline, 256, wpng_info.infile); /* more comment lines */
  291. } while (pnmline[0] == '#');
  292. sscanf(pnmline, "%d", &maxval);
  293. if (wpng_info.width <= 0L || wpng_info.height <= 0L ||
  294. maxval != 255)
  295. {
  296. fprintf(stderr, PROGNAME
  297. ": only positive width/height, maxval == 255 allowed \n");
  298. ++error;
  299. }
  300. wpng_info.sample_depth = 8; /* <==> maxval 255 */
  301. if (!wpng_info.filter) {
  302. /* make outname from inname */
  303. if ((p = strrchr(inname, '.')) == NULL ||
  304. (p - inname) != (len - 4))
  305. {
  306. strcpy(outname, inname);
  307. strcpy(outname+len, ".png");
  308. } else {
  309. len -= 4;
  310. strncpy(outname, inname, len);
  311. strcpy(outname+len, ".png");
  312. }
  313. /* check if outname already exists; if not, open */
  314. if ((wpng_info.outfile = fopen(outname, "rb")) != NULL) {
  315. fprintf(stderr, PROGNAME ": output file exists [%s]\n",
  316. outname);
  317. fclose(wpng_info.outfile);
  318. ++error;
  319. } else if (!(wpng_info.outfile = fopen(outname, "wb"))) {
  320. fprintf(stderr, PROGNAME ": can't open output file [%s]\n",
  321. outname);
  322. ++error;
  323. }
  324. }
  325. }
  326. if (error) {
  327. fclose(wpng_info.infile);
  328. wpng_info.infile = NULL;
  329. if (wpng_info.filter) {
  330. fclose(wpng_info.outfile);
  331. wpng_info.outfile = NULL;
  332. }
  333. }
  334. }
  335. /* if we had any errors, print usage and die horrible death...arrr! */
  336. if (error) {
  337. fprintf(stderr, "\n%s %s: %s\n", PROGNAME, VERSION, APPNAME);
  338. writepng_version_info();
  339. fprintf(stderr, "\n"
  340. "Usage: %s [-gamma exp] [-bgcolor bg] [-text] [-time] [-interlace] pnmfile\n"
  341. "or: ... | %s [-gamma exp] [-bgcolor bg] [-text] [-time] [-interlace] | ...\n"
  342. " exp \ttransfer-function exponent (``gamma'') of the image in\n"
  343. "\t\t floating-point format (e.g., ``%.5f''); if image looks\n"
  344. "\t\t correct on given display system, image gamma is equal to\n"
  345. "\t\t inverse of display-system exponent, i.e., 1 / (LUT * CRT)\n"
  346. "\t\t (where LUT = lookup-table exponent and CRT = CRT exponent;\n"
  347. "\t\t first varies, second is usually 2.2, all are positive)\n"
  348. " bg \tdesired background color for alpha-channel images, in\n"
  349. "\t\t 7-character hex RGB format (e.g., ``#ff7700'' for orange:\n"
  350. "\t\t same as HTML colors)\n"
  351. " -text\tprompt interactively for text info (tEXt chunks)\n"
  352. " -time\tinclude a tIME chunk (last modification time)\n"
  353. " -interlace\twrite interlaced PNG image\n"
  354. "\n"
  355. "pnmfile or stdin must be a binary PGM (`P5'), PPM (`P6') or (extremely\n"
  356. "unofficial and unsupported!) PAM (`P8') file. Currently it is required\n"
  357. "to have maxval == 255 (i.e., no scaling). If pnmfile is specified, it\n"
  358. "is converted to the corresponding PNG file with the same base name but a\n"
  359. "``.png'' extension; files read from stdin are converted and sent to stdout.\n"
  360. "The conversion is progressive (low memory usage) unless interlacing is\n"
  361. "requested; in that case the whole image will be buffered in memory and\n"
  362. "written in one call.\n"
  363. "\n", PROGNAME, PROGNAME, default_gamma);
  364. exit(1);
  365. }
  366. /* prepare the text buffers for libpng's use; note that even though
  367. * PNG's png_text struct includes a length field, we don't have to fill
  368. * it out */
  369. if (text &&
  370. #ifndef DOS_OS2_W32
  371. (keybd = fdopen(fileno(stderr), "r")) != NULL &&
  372. #endif
  373. (textbuf = (char *)malloc((5 + 9)*75)) != NULL)
  374. {
  375. int i, valid, result;
  376. fprintf(stderr,
  377. "Enter text info (no more than 72 characters per line);\n");
  378. fprintf(stderr, "to skip a field, hit the <Enter> key.\n");
  379. /* note: just <Enter> leaves len == 1 */
  380. do {
  381. valid = TRUE;
  382. p = textbuf + TEXT_TITLE_OFFSET;
  383. fprintf(stderr, " Title: ");
  384. fflush(stderr);
  385. if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1) {
  386. if (p[len-1] == '\n')
  387. p[--len] = '\0';
  388. wpng_info.title = p;
  389. wpng_info.have_text |= TEXT_TITLE;
  390. if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) {
  391. fprintf(stderr, " " PROGNAME " warning: character code"
  392. " %u is %sdiscouraged by the PNG\n specification "
  393. "[first occurrence was at character position #%d]\n",
  394. (unsigned)p[result], (p[result] == 27)? "strongly " : "",
  395. result+1);
  396. fflush(stderr);
  397. #ifdef FORBID_LATIN1_CTRL
  398. wpng_info.have_text &= ~TEXT_TITLE;
  399. valid = FALSE;
  400. #else
  401. if (p[result] == 27) { /* escape character */
  402. wpng_info.have_text &= ~TEXT_TITLE;
  403. valid = FALSE;
  404. }
  405. #endif
  406. }
  407. }
  408. } while (!valid);
  409. do {
  410. valid = TRUE;
  411. p = textbuf + TEXT_AUTHOR_OFFSET;
  412. fprintf(stderr, " Author: ");
  413. fflush(stderr);
  414. if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1) {
  415. if (p[len-1] == '\n')
  416. p[--len] = '\0';
  417. wpng_info.author = p;
  418. wpng_info.have_text |= TEXT_AUTHOR;
  419. if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) {
  420. fprintf(stderr, " " PROGNAME " warning: character code"
  421. " %u is %sdiscouraged by the PNG\n specification "
  422. "[first occurrence was at character position #%d]\n",
  423. (unsigned)p[result], (p[result] == 27)? "strongly " : "",
  424. result+1);
  425. fflush(stderr);
  426. #ifdef FORBID_LATIN1_CTRL
  427. wpng_info.have_text &= ~TEXT_AUTHOR;
  428. valid = FALSE;
  429. #else
  430. if (p[result] == 27) { /* escape character */
  431. wpng_info.have_text &= ~TEXT_AUTHOR;
  432. valid = FALSE;
  433. }
  434. #endif
  435. }
  436. }
  437. } while (!valid);
  438. do {
  439. valid = TRUE;
  440. p = textbuf + TEXT_DESC_OFFSET;
  441. fprintf(stderr, " Description (up to 9 lines):\n");
  442. for (i = 1; i < 10; ++i) {
  443. fprintf(stderr, " [%d] ", i);
  444. fflush(stderr);
  445. if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1)
  446. p += len; /* now points at NULL; char before is newline */
  447. else
  448. break;
  449. }
  450. if ((len = p - (textbuf + TEXT_DESC_OFFSET)) > 1) {
  451. if (p[-1] == '\n') {
  452. p[-1] = '\0';
  453. --len;
  454. }
  455. wpng_info.desc = textbuf + TEXT_DESC_OFFSET;
  456. wpng_info.have_text |= TEXT_DESC;
  457. p = textbuf + TEXT_DESC_OFFSET;
  458. if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) {
  459. fprintf(stderr, " " PROGNAME " warning: character code"
  460. " %u is %sdiscouraged by the PNG\n specification "
  461. "[first occurrence was at character position #%d]\n",
  462. (unsigned)p[result], (p[result] == 27)? "strongly " : "",
  463. result+1);
  464. fflush(stderr);
  465. #ifdef FORBID_LATIN1_CTRL
  466. wpng_info.have_text &= ~TEXT_DESC;
  467. valid = FALSE;
  468. #else
  469. if (p[result] == 27) { /* escape character */
  470. wpng_info.have_text &= ~TEXT_DESC;
  471. valid = FALSE;
  472. }
  473. #endif
  474. }
  475. }
  476. } while (!valid);
  477. do {
  478. valid = TRUE;
  479. p = textbuf + TEXT_COPY_OFFSET;
  480. fprintf(stderr, " Copyright: ");
  481. fflush(stderr);
  482. if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1) {
  483. if (p[len-1] == '\n')
  484. p[--len] = '\0';
  485. wpng_info.copyright = p;
  486. wpng_info.have_text |= TEXT_COPY;
  487. if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) {
  488. fprintf(stderr, " " PROGNAME " warning: character code"
  489. " %u is %sdiscouraged by the PNG\n specification "
  490. "[first occurrence was at character position #%d]\n",
  491. (unsigned)p[result], (p[result] == 27)? "strongly " : "",
  492. result+1);
  493. fflush(stderr);
  494. #ifdef FORBID_LATIN1_CTRL
  495. wpng_info.have_text &= ~TEXT_COPY;
  496. valid = FALSE;
  497. #else
  498. if (p[result] == 27) { /* escape character */
  499. wpng_info.have_text &= ~TEXT_COPY;
  500. valid = FALSE;
  501. }
  502. #endif
  503. }
  504. }
  505. } while (!valid);
  506. do {
  507. valid = TRUE;
  508. p = textbuf + TEXT_EMAIL_OFFSET;
  509. fprintf(stderr, " E-mail: ");
  510. fflush(stderr);
  511. if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1) {
  512. if (p[len-1] == '\n')
  513. p[--len] = '\0';
  514. wpng_info.email = p;
  515. wpng_info.have_text |= TEXT_EMAIL;
  516. if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) {
  517. fprintf(stderr, " " PROGNAME " warning: character code"
  518. " %u is %sdiscouraged by the PNG\n specification "
  519. "[first occurrence was at character position #%d]\n",
  520. (unsigned)p[result], (p[result] == 27)? "strongly " : "",
  521. result+1);
  522. fflush(stderr);
  523. #ifdef FORBID_LATIN1_CTRL
  524. wpng_info.have_text &= ~TEXT_EMAIL;
  525. valid = FALSE;
  526. #else
  527. if (p[result] == 27) { /* escape character */
  528. wpng_info.have_text &= ~TEXT_EMAIL;
  529. valid = FALSE;
  530. }
  531. #endif
  532. }
  533. }
  534. } while (!valid);
  535. do {
  536. valid = TRUE;
  537. p = textbuf + TEXT_URL_OFFSET;
  538. fprintf(stderr, " URL: ");
  539. fflush(stderr);
  540. if (FGETS(p, 74, keybd) && (len = strlen(p)) > 1) {
  541. if (p[len-1] == '\n')
  542. p[--len] = '\0';
  543. wpng_info.url = p;
  544. wpng_info.have_text |= TEXT_URL;
  545. if ((result = wpng_isvalid_latin1((uch *)p, len)) >= 0) {
  546. fprintf(stderr, " " PROGNAME " warning: character code"
  547. " %u is %sdiscouraged by the PNG\n specification "
  548. "[first occurrence was at character position #%d]\n",
  549. (unsigned)p[result], (p[result] == 27)? "strongly " : "",
  550. result+1);
  551. fflush(stderr);
  552. #ifdef FORBID_LATIN1_CTRL
  553. wpng_info.have_text &= ~TEXT_URL;
  554. valid = FALSE;
  555. #else
  556. if (p[result] == 27) { /* escape character */
  557. wpng_info.have_text &= ~TEXT_URL;
  558. valid = FALSE;
  559. }
  560. #endif
  561. }
  562. }
  563. } while (!valid);
  564. #ifndef DOS_OS2_W32
  565. fclose(keybd);
  566. #endif
  567. } else if (text) {
  568. fprintf(stderr, PROGNAME ": unable to allocate memory for text\n");
  569. text = FALSE;
  570. wpng_info.have_text = 0;
  571. }
  572. /* allocate libpng stuff, initialize transformations, write pre-IDAT data */
  573. if ((rc = writepng_init(&wpng_info)) != 0) {
  574. switch (rc) {
  575. case 2:
  576. fprintf(stderr, PROGNAME
  577. ": libpng initialization problem (longjmp)\n");
  578. break;
  579. case 4:
  580. fprintf(stderr, PROGNAME ": insufficient memory\n");
  581. break;
  582. case 11:
  583. fprintf(stderr, PROGNAME
  584. ": internal logic error (unexpected PNM type)\n");
  585. break;
  586. default:
  587. fprintf(stderr, PROGNAME
  588. ": unknown writepng_init() error\n");
  589. break;
  590. }
  591. exit(rc);
  592. }
  593. /* free textbuf, since it's a completely local variable and all text info
  594. * has just been written to the PNG file */
  595. if (text && textbuf) {
  596. free(textbuf);
  597. textbuf = NULL;
  598. }
  599. /* calculate rowbytes on basis of image type; note that this becomes much
  600. * more complicated if we choose to support PBM type, ASCII PNM types, or
  601. * 16-bit-per-sample binary data [currently not an official NetPBM type] */
  602. if (wpng_info.pnmtype == 5)
  603. rowbytes = wpng_info.width;
  604. else if (wpng_info.pnmtype == 6)
  605. rowbytes = wpng_info.width * 3;
  606. else /* if (wpng_info.pnmtype == 8) */
  607. rowbytes = wpng_info.width * 4;
  608. /* read and write the image, either in its entirety (if writing interlaced
  609. * PNG) or row by row (if non-interlaced) */
  610. fprintf(stderr, "Encoding image data...\n");
  611. fflush(stderr);
  612. if (wpng_info.interlaced) {
  613. long i;
  614. ulg bytes;
  615. ulg image_bytes = rowbytes * wpng_info.height; /* overflow? */
  616. wpng_info.image_data = (uch *)malloc(image_bytes);
  617. wpng_info.row_pointers = (uch **)malloc(wpng_info.height*sizeof(uch *));
  618. if (wpng_info.image_data == NULL || wpng_info.row_pointers == NULL) {
  619. fprintf(stderr, PROGNAME ": insufficient memory for image data\n");
  620. writepng_cleanup(&wpng_info);
  621. wpng_cleanup();
  622. exit(5);
  623. }
  624. for (i = 0; i < wpng_info.height; ++i)
  625. wpng_info.row_pointers[i] = wpng_info.image_data + i*rowbytes;
  626. bytes = fread(wpng_info.image_data, 1, image_bytes, wpng_info.infile);
  627. if (bytes != image_bytes) {
  628. fprintf(stderr, PROGNAME ": expected %lu bytes, got %lu bytes\n",
  629. image_bytes, bytes);
  630. fprintf(stderr, " (continuing anyway)\n");
  631. }
  632. if (writepng_encode_image(&wpng_info) != 0) {
  633. fprintf(stderr, PROGNAME
  634. ": libpng problem (longjmp) while writing image data\n");
  635. writepng_cleanup(&wpng_info);
  636. wpng_cleanup();
  637. exit(2);
  638. }
  639. } else /* not interlaced: write progressively (row by row) */ {
  640. long j;
  641. ulg bytes;
  642. wpng_info.image_data = (uch *)malloc(rowbytes);
  643. if (wpng_info.image_data == NULL) {
  644. fprintf(stderr, PROGNAME ": insufficient memory for row data\n");
  645. writepng_cleanup(&wpng_info);
  646. wpng_cleanup();
  647. exit(5);
  648. }
  649. error = 0;
  650. for (j = wpng_info.height; j > 0L; --j) {
  651. bytes = fread(wpng_info.image_data, 1, rowbytes, wpng_info.infile);
  652. if (bytes != rowbytes) {
  653. fprintf(stderr, PROGNAME
  654. ": expected %lu bytes, got %lu bytes (row %ld)\n", rowbytes,
  655. bytes, wpng_info.height-j);
  656. ++error;
  657. break;
  658. }
  659. if (writepng_encode_row(&wpng_info) != 0) {
  660. fprintf(stderr, PROGNAME
  661. ": libpng problem (longjmp) while writing row %ld\n",
  662. wpng_info.height-j);
  663. ++error;
  664. break;
  665. }
  666. }
  667. if (error) {
  668. writepng_cleanup(&wpng_info);
  669. wpng_cleanup();
  670. exit(2);
  671. }
  672. if (writepng_encode_finish(&wpng_info) != 0) {
  673. fprintf(stderr, PROGNAME ": error on final libpng call\n");
  674. writepng_cleanup(&wpng_info);
  675. wpng_cleanup();
  676. exit(2);
  677. }
  678. }
  679. /* OK, we're done (successfully): clean up all resources and quit */
  680. fprintf(stderr, "Done.\n");
  681. fflush(stderr);
  682. writepng_cleanup(&wpng_info);
  683. wpng_cleanup();
  684. return 0;
  685. }
  686. static int wpng_isvalid_latin1(uch *p, int len)
  687. {
  688. int i, result = -1;
  689. for (i = 0; i < len; ++i) {
  690. if (p[i] == 10 || (p[i] > 31 && p[i] < 127) || p[i] > 160)
  691. continue; /* character is completely OK */
  692. if (result < 0 || (p[result] != 27 && p[i] == 27))
  693. result = i; /* mark location of first questionable one */
  694. } /* or of first escape character (bad) */
  695. return result;
  696. }
  697. static void wpng_cleanup(void)
  698. {
  699. if (wpng_info.outfile) {
  700. fclose(wpng_info.outfile);
  701. wpng_info.outfile = NULL;
  702. }
  703. if (wpng_info.infile) {
  704. fclose(wpng_info.infile);
  705. wpng_info.infile = NULL;
  706. }
  707. if (wpng_info.image_data) {
  708. free(wpng_info.image_data);
  709. wpng_info.image_data = NULL;
  710. }
  711. if (wpng_info.row_pointers) {
  712. free(wpng_info.row_pointers);
  713. wpng_info.row_pointers = NULL;
  714. }
  715. }
  716. #ifdef DOS_OS2_W32
  717. static char *dos_kbd_gets(char *buf, int len)
  718. {
  719. int ch, count=0;
  720. do {
  721. buf[count++] = ch = getche();
  722. } while (ch != '\r' && count < len-1);
  723. buf[count--] = '\0'; /* terminate string */
  724. if (buf[count] == '\r') /* Enter key makes CR, so change to newline */
  725. buf[count] = '\n';
  726. fprintf(stderr, "\n"); /* Enter key does *not* cause a newline */
  727. fflush(stderr);
  728. return buf;
  729. }
  730. #endif /* DOS_OS2_W32 */