This file is indexed.

/usr/share/doc/png-definitive-guide/html/chapter13.html is in png-definitive-guide 20060430-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>Reading PNG Images (PNG: The Definitive Guide)</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">

<!-- http://www.w3.org/TR/REC-CSS2/box.html -->
<STYLE TYPE="text/css">
  P { margin-bottom: 0em }
  UL {
    margin-bottom: 0em;
    margin-top: 0em;
    list-style: disc;
  }
  LI {
    padding: 0px 0px 0px 0px;
    margin: 0px 0px 0px 0px;
  }
</STYLE>

<LINK REV="made" HREF="http://pobox.com/~newt/greg_contact.html">
<!--  Copyright (c) 1999 O'Reilly and Associates.  -->
<!--  Copyright (c) 2002-2006 Greg Roelofs.  -->
</HEAD>

<body bgcolor="#ffffff" text="#000000">


<hr> <!-- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -->

<a href="chapter12.html"><img width=24 height=13 border=0 align="left"
 src="images/prev.png" alt="&lt;-"></a>

<a href="chapter14.html"><img width=24 height=13 border=0 align="right"
 src="images/next.png" alt="-&gt;"></a>

<div align="center">
  <a href="chapter12.html"><font size="-1" color="#000000"
   ><b>PREVIOUS</b></font></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a
     href="toc.html"><font size="-1" color="#000000"
   ><b>CONTENTS</b></font></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a
     href="chapter14.html"><font size="-1" color="#000000"
   ><b>NEXT</b></font></a>
</div>

<hr> <!-- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -->


<h1 class="chapter">Chapter 13. Reading PNG Images</h1>

<div class="htmltoc"><h4 class="tochead">Contents:</h4><p>
<a href="#png.ch13.div.1">13.1. A libpng-Based, PNG-Reading Demo Program</a><br />
<a href="#png.ch13.div.2">13.2. Preliminaries</a><br />
<a href="#png.ch13.div.3">13.3. readpng_init()</a><br />
<a href="#png.ch13.div.4">13.4. readpng_get_bgcolor()</a><br />
<a href="#png.ch13.div.5">13.5. Design Decisions</a><br />
<a href="#png.ch13.div.6">13.6. Gamma and Color Correction</a><br />
<a href="#png.ch13.div.7">13.7. readpng_get_image()</a><br />
<a href="#png.ch13.div.8">13.8. readpng_cleanup()</a><br />
<a href="#png.ch13.div.9">13.9. Compositing and Displaying the Image</a><br />
<a href="#png.ch13.div.10">13.10. Getting the Source Code</a><br />
<a href="#png.ch13.div.11">13.11. Alternative Approaches</a><br />
</p></div>



<p>As with almost any kind of programming project, there are numerous
alternatives one can take when writing a PNG-supporting program. Complete
or partial code for reading and/or writing PNGs is available for the C, C++,
Java, Pascal, tcl/tk, Python, and Visual Basic languages, at a minimum; some
of it is in the form of commercial libraries, some as free source code, and
some as a combination of both. Many of these in alternatives are listed in
<a href="chapter16.html">Chapter 16, "Other Libraries and Concluding Remarks"</a>.
One can even read and write PNG images directly, in effect implementing 
one's own PNG library, but this is a rather large undertaking and is
generally not recommended except under special circumstances.</p>


<p>
<a name="INDEX-983" />
<a name="INDEX-984" />
<a name="INDEX-985" />
<a name="INDEX-986" />
<a name="INDEX-987" />
<a name="INDEX-988" />
The granddaddy of all PNG libraries is <em class="emphasis">libpng</em>,
the free reference library available as Standard (ANSI) C source code and
used by many, if not most, PNG-supporting applications. It uses the
similarly free <em class="emphasis">zlib</em> library (portable C source
code) for compression and decompression, and in these next few chapters
I'll provide detailed demonstrations of how to write programs with both.</p>


<div class="sect1"><a name="png.ch13.div.1" />
<h2 class="sect1">13.1. A libpng-Based, PNG-Reading Demo Program</h2>


<p><a name="INDEX-989" />
<a name="INDEX-990" />In order to provide a concrete demonstration of how to use libpng to read PNG
images, I have written a complete (albeit basic) PNG viewer in Standard C.
It consists of two main source files: a platform-independent one that
includes all of the PNG- and libpng-specific code (<em class="emphasis">readpng.c</em>),
<a name="INDEX-991" />
<a name="INDEX-992" />
<a name="INDEX-993" />and a platform-dependent file that contains all of the user interface and
display code. The idea is that the PNG code (the ``back end'') is generic
enough that it can be dropped into almost any image-reading C program, whether
a viewer, editor, converter, or something else; it is the part that is of
primary interest to us. The platform-dependent code (``front end'') is
functional--yes, it really works!--but it is not complete or robust
enough to be considered a final product.</p>


<p>The back-end code was written for libpng version 1.0.3, but it should work
with any 1.x release of the library. Later releases of libpng may add new
interfaces, but the functions used here are expected to remain available
more or less indefinitely, for backward compatibility. As for the front-end
code, two versions are currently available: one for the X Window System
<a name="INDEX-994" />
<a name="INDEX-995" />
<a name="INDEX-996" />
<a name="INDEX-997" />(<em class="emphasis">rpng-x.c</em>; mainly for Unix systems, but also potentially VMS and OS/2),
and one for Windows 95/98 and NT (<em class="emphasis">rpng-win.c</em>). I will avoid getting


into the details of these as much as possible, but where it is unavoidable,
I will either use excerpts that are common to both or else point out the
differences between the two versions. Complete source listings for both
flavors can be found at <a href="http://www.libpng.org/pub/png/pngbook.html">http://www.libpng.org/pub/png/pngbook.html</a>.</p>


<p>The basic PNG reader has the following features: it is file-based, it
reads and displays a single image and then quits, and it is concerned
only with reading and decoding that image--it has
nothing better to do and can afford to wait on file input/output (I/O)
and other potentially slow but non-CPU-intensive tasks. In other
words, its characteristics are typical of standalone image viewers,
converters, and many image editors, but not of web browsers. Browsers
usually read from a network, which is often extremely slow compared to
disk access (for example, due to limited modem bandwidth or just
congested Internet sites), and they are usually busy formatting text
and decoding several images at the same time--they <em class="emphasis">do</em>
have something better to do than to wait for the rest of the file to
show up. I'll address these issues in 
<a href="chapter14.html">Chapter 14, "Reading PNG Images Progressively"</a>, 
with the second demo program.</p>
</div>

















</div>
<div class="sect1"><a name="png.ch13.div.2" />
<h2 class="sect1">13.2. Preliminaries</h2>


<p><a name="INDEX-998" />
<a name="INDEX-999" />Before we get into the heart of our basic demo program, I'll touch on a
couple of mundane but nevertheless important details. The first is the
libpng header file, <em class="emphasis">png.h</em>, which defines all of the libpng datatypes,
declares all of the public function prototypes, and includes some useful
macros. It must be included in any module that makes libpng function calls;
in our case, we've segregated all of those in <em class="emphasis">readpng.c</em>, so that's
the only place we need to include <em class="emphasis">png.h</em>:</p>


<blockquote><pre class="code">#include "png.h"</pre></blockquote>


<p><a name="INDEX-1000" />Because <em class="emphasis">png.h</em> includes <em class="emphasis">zlib.h</em>, we need not include it
explicitly, and most programs need not even worry about it, since there is
rarely a need for the user's program to call zlib routines directly. But
in our case we do want to make sure <em class="emphasis">zlib.h</em> is included somewhere. The
reason for this is the second mundane detail: programs tend to be updated
over time, and this often involves plugging in a newer version of a support
library like libpng or zlib. When following up on a bug 
report, particularly with regard to software for which the source code
is available (like the demo programs in this book), it is generally
useful to know as much as possible about the version that exhibits the
bug. In the presence of shared (dynamically linked) libraries, that's
even more important. So as part of our demo program's usage
screen--the poor man's version of an ``about box''--we call a very
small routine in <em class="emphasis">readpng.c</em> that indicates not only the versions
of libpng and zlib with which it was compiled, but also the versions
it is currently using:
<a name="INDEX-1001" /></p>


<blockquote><pre class="code">void readpng_version_info()
{
    fprintf(stderr, "   Compiled with libpng %s; using libpng %s.\n",
      PNG_LIBPNG_VER_STRING, png_libpng_ver);
    fprintf(stderr, "   Compiled with zlib %s; using zlib %s.\n",
      ZLIB_VERSION, zlib_version);
}</pre></blockquote>


<p>The uppercase values here are macros defined in the <em class="emphasis">png.h</em> and
<em class="emphasis">zlib.h</em> header files; they indicate the compile-time versions.
The lowercase variables are globals exported by the two libraries, so they
give the versions actually in use at the time the program is run. Ideally,
each pair of version numbers will match, but it is not unusual for the user,
and sometimes even the programmer, to be caught by an unsuspected mismatch.
<a name="INDEX-1002" />
<a name="INDEX-1003" />
<a name="INDEX-1004" />
</p>


















</div>
<div class="sect1"><a name="png.ch13.div.3" />
<h2 class="sect1">13.3. readpng_init()</h2>


<p><a name="INDEX-1005" />
<a name="INDEX-1006" />The ``real'' code in the basic PNG reader begins when the image file
is opened (in <em class="emphasis">binary</em> mode!) and its stream pointer passed to our
libpng-initialization routine,
<b class="emphasis-bold">readpng_init()</b>. <b class="emphasis-bold">readpng_init()</b> also takes two pointers
to long integers representing the height and width of the image:</p>


<blockquote><pre class="code">int readpng_init(FILE *infile, long *pWidth, long *pHeight)</pre></blockquote>


<p>We can get away with using <b class="emphasis-bold">long</b>s instead of <b class="emphasis-bold">unsigned</b>
<b class="emphasis-bold">long</b>s because the PNG specification requires that image
dimensions not exceed
2<sup class="superscript">31</sup> - 1.<a href="#FOOTNOTE-99">[99]</a>
<b class="emphasis-bold">readpng_init()</b> returns a status value; zero will be used to indicate
success, and various nonzero values will indicate different errors.</p><blockquote class="footnote">


<a name="FOOTNOTE-99" /><p>[99] Of course, an image with dimensions that big is likely to exhaust the real
and virtual memory on most systems, but we won't worry about that here.</p>


</blockquote>


<p>The first thing we do in <b class="emphasis-bold">readpng_init()</b> is read the first 8 bytes
of the file and make sure they match the PNG signature bytes; if they don't,
there is no need to waste time setting up libpng, allocating memory and so
forth. Ordinarily one would read a block of 512 bytes or more, but libpng
does its own buffered reads and requires that no more than 8 bytes have
been read before handing off control. So 8 bytes it is:</p>


<blockquote><pre class="code">    uch sig[8];
  
    fread(sig, 1, 8, infile);
    if (!png_check_sig(sig, 8))
        return 1;   /* bad signature */</pre></blockquote>


<p><a name="INDEX-1007" />There are two things to note here. The first is the use of the <b class="emphasis-bold">uch</b>
typedef, which stands for <b class="emphasis-bold">unsigned char</b>; we use it for brevity and
will likewise employ <b class="emphasis-bold">ush</b> and <b class="emphasis-bold">ulg</b> for <b class="emphasis-bold">unsigned short</b>
and <b class="emphasis-bold">unsigned long</b>, respectively.<a href="#FOOTNOTE-100">[100]</a>
<a name="INDEX-1008" />
<a name="INDEX-1009" />
The second is that <b class="emphasis-bold">png_check_sig()</b> and its slightly more general
sibling <b class="emphasis-bold">png_sig_cmp()</b> are unique among libpng routines in that they
require no reference to any structures, nor any knowledge of the state of the
PNG stream.</p><blockquote class="footnote">


<a name="FOOTNOTE-100" /><p>[100] Other typedefs, such as <b class="emphasis-bold">uchar</b> and <b class="emphasis-bold">u_char</b>, are more common
and recognizable, but these are sometimes also defined by system header files.
Unlike macros, there is no way to test for the existence of a C typedef, and
a repeated or conflicting typedef definition is treated as an error by most
compilers.</p>


</blockquote>


<p>Assuming the file checked out with a proper PNG signature, the next thing
to do is set up the PNG structs that will hold all of the basic information
associated with the PNG image. The use of two or three structs instead of
one is historical baggage; a future, incompatible version of the library is
likely to hide one or both from the user and perhaps instead employ an image
ID tag to keep track of multiple images. But for now two are necessary:</p>


<a name="INDEX-1009.01-missing" />
<a name="INDEX-1009.02-missing" />
<blockquote>
<pre class="code">    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL,
      NULL);
    if (!png_ptr)
        return 4;   /* out of memory */
  
    info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr) {
        png_destroy_read_struct(&amp;png_ptr, NULL, NULL);
        return 4;   /* out of memory */
    }</pre>
</blockquote>


<p>The struct at which <b class="emphasis-bold">png_ptr</b> points is used internally by
libpng to keep track of the current state of the PNG image at any
given moment; <b class="emphasis-bold">info_ptr</b> is used to indicate what its state will
be after all of the user-requested transformations are performed. One
can also allocate a second information struct, usually referenced via an
<b class="emphasis-bold">end_ptr</b> variable; this can be used to hold all of the PNG chunk
information that comes after the image data, in case it is important to
keep pre- and post-IDAT information separate (as in an image editor, which should
preserve as much of the existing PNG structure as possible). For this
application, we don't care where the chunk 
information comes from, so we will forego the <b class="emphasis-bold">end_ptr</b>
information struct and direct everything to <b class="emphasis-bold">info_ptr</b>.</p>


<p>One or both of <b class="emphasis-bold">png_ptr</b> and <b class="emphasis-bold">info_ptr</b> are used in all remaining
libpng calls, so we have simply declared them global in this case:</p>


<blockquote><pre class="code">static png_structp png_ptr;
static png_infop info_ptr;</pre></blockquote>


<p>Global variables don't work in reentrant programs, where the same
routines may get called in parallel to handle different images, but this
demo program is explicitly designed to handle only one image at a time.</p>


<blockquote><table border="1" cellpadding="6"><tr><td><h4 class="objtitle">The Dark Side</h4>



<p>

Let's take a brief break in order to make a couple of points about
programming practices, mostly bad ones. The first is that old
<a name="INDEX-1010" />
<a name="INDEX-1011" />versions of libpng (pre-1.0) required one to allocate memory
for the two structs manually, via <b class="emphasis-bold">malloc()</b> or a similar function. This is
strongly discouraged now. The reason is that libpng continues to evolve,
and in an environment with shared or dynamically linked libraries (DLLs),
a program that was compiled with an older version of libpng may suddenly
find itself using a new version with larger or smaller structs. The
<a name="INDEX-1012" /><b class="emphasis-bold">png_create_XXXX_struct()</b> functions allow the version of the library
that is actually being used to allocate the proper structs for itself,
avoiding many problems down the road.</p>


<p><a name="INDEX-1013" />
<a name="INDEX-1014" />Similarly, old versions of libpng encouraged or even required the user
to access members of the structs directly--for example, the image
height might be available as <b class="emphasis-bold">info_ptr-&gt;height</b> or
<b class="emphasis-bold">png_ptr-&gt;height</b> or even (as in this case) both! This was bad,
not only because similar struct members sometimes had different values
that could change at different times, but also because any program
that is compiled to use such an approach effectively assumes that the
same struct member is always at the same offset from the beginning of
the struct. This is not a serious problem if the libpng routines are
statically linked, although there is some danger that things will
break if the program is later recompiled with a newer version of
libpng. But even if libpng itself never changes the definition of the
struct's contents, a user who compiles a new DLL version with slightly
different compilation parameters--for example, with
structure-packing turned on--may have suddenly shifted things around
so they appear at new offsets. libpng can also be compiled with
certain features disabled, which in turn eliminates the corresponding
structure members from the definition of the structs and therefore
alters the offsets of any later structure members. And I already
mentioned that libpng is evolving: new things get added to the structs
periodically, and perhaps an existing structure member is found to
have been defined with an incorrect size, which is then corrected. The
upshot is that direct access to struct members is very, very
bad. Don't do it. Don't let your friends do it. We certainly won't be
doing it here.</p>


</td></tr></table></blockquote>

<p>



The pointers are now set up and pointing at allocated structs of the
proper sizes--or else we've returned to the main program with an
error. The next step is to set up a small amount of generic
error-handling code. Instead of depending on error codes returned
from each of its component functions, libpng employs a more efficient
<a name="INDEX-1015" />
<a name="INDEX-1016" />but rather uglier approach involving the <b class="emphasis-bold">setjmp()</b> and
<b class="emphasis-bold">longjmp()</b> functions. Defined in the standard C header file
<em class="emphasis">setjmp.h</em> (which is automatically included in <em class="emphasis">pngconf.h</em>,
itself included in <em class="emphasis">png.h</em>), these routines effectively amount to
a giant <b class="emphasis-bold">goto</b> statement that can cross function boundaries.
This avoids a lot of conditional testing (if (error)
<b class="emphasis-bold">return error;</b>), but it can make the program flow harder to
understand in the case of errors. Nevertheless, that's what libpng
uses by default, so that's what we use here:</p>


<blockquote><pre class="code">    if (setjmp(png_ptr-&gt;jmpbuf)) {
        png_destroy_read_struct(&amp;png_ptr, &amp;info_ptr, NULL);
        return 2;
    }</pre></blockquote>


<p>The way to read this code fragment is as follows: the first time through,
the <b class="emphasis-bold">setjmp()</b> call saves the state of the program (registers, stack,
and so on) in <b class="emphasis-bold">png_ptr-&gt;jmpbuf</b> and returns successfully--that is, with a
return value of zero--thus avoiding the contents of the if-block. But if an
error later occurs and libpng invokes <b class="emphasis-bold">longjmp()</b> on the same copy of
<b class="emphasis-bold">png_ptr-&gt;jmpbuf</b>, control suddenly returns to the if-block as
if <b class="emphasis-bold">setjmp()</b> had just returned, but this time with a nonzero return
value. The if-test then evaluates to TRUE, so the PNG structs are
destroyed and we return to the main program.</p>


<p><a name="INDEX-1017" />But wait! Didn't I just finish lecturing about the evils of direct access
to structure members? Yet here I am, referring to the <b class="emphasis-bold">jmpbuf</b>
member of the main PNG struct. The reason is that there is simply no other
way to get a pointer to the <b class="emphasis-bold">longjmp</b> buffer in any release of libpng through
version 1.0.3. And, sadly, there may not be any clean and backward-compatible
way to work around this limitation in future releases, either. The unfortunate
fact is that the ANSI committee responsible for defining the C language and
<a name="INDEX-1018" />standard C library managed to standardize <b class="emphasis-bold">jmp_buf</b> in such a way that
one cannot reliably pass pointers to it, nor can one be certain that its
size is constant even on a single system. In particular, if a certain macro
is defined when libpng is compiled but not for a libpng-using application,
then <b class="emphasis-bold">jmp_buf</b> may have different sizes when the application calls
<b class="emphasis-bold">setjmp()</b> and when libpng calls <b class="emphasis-bold">longjmp()</b>. The resulting
inconsistency is more likely than not to cause the application to crash.
<a name="INDEX-1019" />
<a name="INDEX-1020" />
</p>


<p><a name="INDEX-1021" />
<a name="INDEX-1022" />The solution, which is already possible with current libpng releases and
will probably be required as of some future version, is to install a custom
error handler. This is simply a user function that libpng calls instead of
its own <b class="emphasis-bold">longjmp()</b>-based error handler whenever an error is encountered;
like <b class="emphasis-bold">longjmp()</b>, it is not expected to return. But there is no problem
at all if the custom error handler itself calls <b class="emphasis-bold">longjmp()</b>: since
this happens within the application's own code space, its concept of
<b class="emphasis-bold">jmp_buf</b> is completely consistent with that of the code that calls
<b class="emphasis-bold">setjmp()</b> elsewhere in the application. Indeed, there is no longer any
need to use the <b class="emphasis-bold">jmpbuf</b> element of the main libpng struct with this
approach--the application can maintain its own <b class="emphasis-bold">jmp_buf</b>.
I will demonstrate this safer approach in <a href="chapter14.html">Chapter 14, "Reading PNG Images Progressively"</a>.
</p>


<p><a name="INDEX-1023" />Note the use of <b class="emphasis-bold">png_destroy_read_struct()</b> to let libpng free
any memory associated with the PNG structs. We used it earlier, too,
for cases in which creating the info struct failed; then we passed
<b class="emphasis-bold">png_ptr</b> and two NULLs. Here we pass <b class="emphasis-bold">png_ptr</b>,
<b class="emphasis-bold">info_ptr</b> and one NULL. Had we allocated the second info
struct (<b class="emphasis-bold">end_ptr</b>), the third argument would point at it, or,
more precisely, at its pointer, so that <b class="emphasis-bold">end_ptr</b> itself
could be set to NULL after the struct is freed.</p>


<p>Having gotten all of the petty housekeeping details out of the way, we next
set up libpng so it can read the PNG file, and then we begin doing so:</p>


<blockquote><pre class="code">    png_init_io(png_ptr, infile);
    png_set_sig_bytes(png_ptr, 8);
    png_read_info(png_ptr, info_ptr);</pre></blockquote>


<p><a name="INDEX-1024" />The <b class="emphasis-bold">png_init_io()</b> function takes our file stream pointer
(<b class="emphasis-bold">infile</b>) and stores it in the <b class="emphasis-bold">png_ptr</b> struct for later use.
<b class="emphasis-bold">png_set_sig_bytes()</b> lets libpng know that we already checked the
8 signature bytes, so it should not expect to find them at the current
file pointer location.</p>


<p><a name="INDEX-1025" /><b class="emphasis-bold">png_read_info()</b> is the first libpng call we've seen that does any
real work. It reads and processes not only the PNG file's IHDR chunk but
also any other chunks up to the first IDAT (i.e., everything before the image
data). For colormapped images this includes the PLTE chunk and possibly tRNS
and bKGD chunks. It typically also includes a gAMA chunk; perhaps cHRM, sRGB,
or iCCP; and often tIME and some tEXt chunks. All this information is
stored in the information struct and some in the PNG struct, too, but for now, all
we care about is the contents of IHDR--specifically, the image width and
height:</p>


<blockquote><pre class="code">    png_get_IHDR(png_ptr, info_ptr, &amp;width, &amp;height, &amp;bit_depth,
      &amp;color_type, NULL, NULL, NULL);
    *pWidth = width;
    *pHeight = height;
  
    return 0;</pre></blockquote>


<p>Once again, since this is a single-image program, I've been lazy and
used global variables not only for the image dimensions but also for
the image's bit depth (bits per sample--R, G, B, A, or gray--or
per palette index, <em class="emphasis">not</em> per pixel) and color type. The image
dimensions are also passed back to the main program via the last two
arguments of <b class="emphasis-bold">readpng_init()</b>. The other two variables will be
used later. If we were interested in whether the image is interlaced
or what compression and filtering methods it uses, we would use actual
values instead of NULLs for the last three arguments to
<a name="INDEX-1026" />
<a name="INDEX-1027" /><b class="emphasis-bold">png_get_IHDR()</b>. Note that the PNG 1.0 and 1.1 specifications
define only a single allowed value (0) for either the compression type
or the filtering method. In this context, compression type 0 is the
deflate method with a maximum window size of 32 KB, and filtering
method 0 is PNG's per-row adaptive method with five possible filter
types. See <a href="chapter09.html">Chapter 9, "Compression and Filtering"</a>, for details.</p>


<p>That wraps up our <b class="emphasis-bold">readpng_init()</b> function. Back in the main program,
various things relating to the windowing system are initialized, but before
the display window itself is created, we potentially make one more <b class="emphasis-bold">readpng</b>
call to see if the image includes its own background color. In fact,
this function could have been incorporated into <b class="emphasis-bold">readpng_init()</b>,
particularly if all program parameters used by the back-end <b class="emphasis-bold">readpng</b> functions
and the front-end display routines were passed via an application-specific
struct, but we didn't happen to set things up that way. Also, note that this
second <b class="emphasis-bold">readpng</b> call is unnecessary if the user has already specified a
particular background color to be used. In this program, a simple command-line
argument is used, but a more sophisticated application might employ a graphical
color wheel, RGB sliders, or some other color-choosing representation.
<a name="INDEX-1028" />
<a name="INDEX-1029" />
</p>


















</div>
<div class="sect1"><a name="png.ch13.div.4" />
<h2 class="sect1">13.4. readpng_get_bgcolor()</h2>


<p><a name="INDEX-1030" />
<a name="INDEX-1031" />
<a name="INDEX-1032" />
<a name="INDEX-1033" />In any case, assuming the user did not specify a background color, we call
<b class="emphasis-bold">readpng_get_bgcolor()</b> to check the PNG file for one. It takes as
arguments pointers to three unsigned character values:</p>


<blockquote><pre class="code">int readpng_get_bgcolor(uch *red, uch *green, uch *blue)</pre></blockquote>


<p>As before, we start with a <b class="emphasis-bold">setjmp()</b> block to handle libpng errors,
then check whether the PNG file had a bKGD chunk:</p>


<blockquote><pre class="code">    if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_bKGD))
        return 1;</pre></blockquote>


<p><a name="INDEX-1034" />
<a name="INDEX-1035" />
<a name="INDEX-1036" />Assuming the <b class="emphasis-bold">png_get_valid()</b> call returned a nonzero value, we
next have libpng give us a pointer to a small struct containing the bKGD 
color information:</p>


<blockquote><pre class="code">    png_color_16p pBackground;
 
    png_get_bKGD(png_ptr, info_ptr, &amp;pBackground);</pre></blockquote>


<p>(<b class="emphasis-bold">pBackground</b> was defined at the top of the function.)
<b class="emphasis-bold">pBackground</b> now points at a <b class="emphasis-bold">png_color_16</b> struct, which is defined
as follows:
<a name="INDEX-1037" /></p>


<blockquote><pre class="code">typedef struct png_color_16_struct
{
    png_byte index;
    png_uint_16 red;
    png_uint_16 green;
    png_uint_16 blue;
    png_uint_16 gray;
} png_color_16;</pre></blockquote>


<p>As suggested by the struct members' names, not all of them are valid with
all PNG image types. The first member, <b class="emphasis-bold">index</b>, is only valid with
palette-based images, for example, and <b class="emphasis-bold">gray</b> is only valid with
grayscale images. But it is one of libpng's handy little features (presently
undocumented) that the <b class="emphasis-bold">red</b>, <b class="emphasis-bold">green</b>, and <b class="emphasis-bold">blue</b> struct
members are always valid, and those happen to be precisely the values we want.</p>


<p>The other thing to note, however, is that the elements we need are defined
as <b class="emphasis-bold">png_uint_16</b>, i.e., as 16-bit (or larger)
unsigned integers. That
<a name="INDEX-1037.01-new" />
suggests that the color values we get back may depend on the bit depth of the
image, which is indeed the case. In fact, this is true regardless of whether
the calling program requested libpng to convert 16-bit values or 1-, 2-, and
4-bit values to 8-bit; this is another currently undocumented tidbit. We'll
be feeding all of these little gotchas back to the libpng maintainer, however,
so one can assume that the documentation will be slightly more complete by
the time this book is published.</p>


<p>Since we'll be dealing only with 8-bit
samples in this program, and, in particular, since the arguments to
<b class="emphasis-bold">readpng_get_bgcolor()</b> are pointers to unsigned (8-bit) characters,
we need to shift the high-order bits down in the case of 16-bit data or
expand them in the case of low-bit-depth values (only possible with grayscale
images). And either way, we need to pass the values back to the main program.
Thus:</p>


<blockquote><pre class="code">    if (bit_depth == 16) {
        *red   = pBackground-&gt;red   &gt;&gt; 8;
        *green = pBackground-&gt;green &gt;&gt; 8;
        *blue  = pBackground-&gt;blue  &gt;&gt; 8;
    } else if (color_type == PNG_COLOR_TYPE_GRAY &amp;&amp; bit_depth &lt; 8) {
        if (bit_depth == 1)
            *red = *green = *blue = pBackground-&gt;gray? 255 : 0;
        else if (bit_depth == 2)   /* i.e., max value is 3 */
            *red = *green = *blue = (255/3) * pBackground-&gt;gray;
        else /* bit_depth == 4 */  /* i.e., max value is 15 */
            *red = *green = *blue = (255/15) * pBackground-&gt;gray;
    } else {
        *red   = pBackground-&gt;red;
        *green = pBackground-&gt;green;
        *blue  = pBackground-&gt;blue;
    }
  
    return 0;</pre></blockquote>


<p>With that, the main program now has enough information to create an
image window of the proper size and fill it with the background color,
which it does. The
<a href="fig_C5.html#png.color.fig.5-row1">top row of Figure C-5</a> in
the color insert shows
the two cases: the middle image is displayed with the background color
specified in the PNG file itself, while the image on the right is
shown with a user-specified background color.</p>


<p><a name="INDEX-1038" />The main program next calls the heart of the <b class="emphasis-bold">readpng</b> code:
<b class="emphasis-bold">readpng_get_image()</b>, which sets the desired libpng
transformations, allocates a PNG image buffer, decodes the image, and
returns a pointer to the raw data. Before we look at that in
detail, we should first discuss some of the design decisions that led
to it.
<a name="INDEX-1039" />
<a name="INDEX-1040" />
<a name="INDEX-1041" />
<a name="INDEX-1042" />
</p>


















</div>
<div class="sect1"><a name="png.ch13.div.5" />
<h2 class="sect1">13.5. Design Decisions</h2>


<p>We decided at the outset that we didn't
want to deal with a lot of PNG bit depths; we have plenty of that in the
front-end code (at least for the X version...sigh). Being fond of alpha
transparency and the nice effects it can produce, we did want to retain
full transparency information, however. In both cases, we were willing to sacrifice
a minimal memory footprint in favor of simplicity and, to some extent, speed.
Thus, we chose to expand or reduce all PNG image types to 24-bit RGB,
optionally with a full 8-bit alpha channel. In other words, the output
would always be either three channels (RGB) or four channels (RGBA).</p>


<p>Handling <em class="emphasis">all</em> alpha blending on our own, in the front end, is not
strictly necessary. In the case of a flat background color, which is all I've
discussed so far, libpng can be instructed to blend the background color
(either from the PNG file or as supplied by the user) with the foreground
pixels, thereby eliminating the alpha channel; the relevant function is
<b class="emphasis-bold">png_set_background()</b>. The result would have been a
single output format to deal with: three-channel, 24-bit RGB. But we had
in mind from the outset the possibility of loading or generating a complete
background image, not just a background color, and libpng currently has no
provision for blending two images.</p>


















</div>
<div class="sect1"><a name="png.ch13.div.6" />
<h2 class="sect1">13.6. Gamma and Color Correction</h2>


<p><a name="INDEX-1043" />
<a name="INDEX-1044" />
<a name="INDEX-1045" />Since this routine is also where any gamma and color correction (recall
<a href="chapter10.html">Chapter 10, "Gamma Correction and Precision Color"</a>) would take place,
we should step back a moment and look at how
the main program deals with that. First I have a confession: I did not
attempt any color correction. (Truly, I am scum.) But this does not
excuse you, the reader, from supporting it, at least in higher-end
applications! The X Window System's base library, Xlib, has included the
X Color Management System since X11R5; it is accessed via the Xcms functions,
an extensive API supporting everything from color-space conversion to gamut
compression. Apple supports the ColorSync system on the Macintosh and will
<a name="INDEX-1046" />be releasing a version for Windows. And Microsoft, if not already supporting
the sRGB color space natively in recent releases of Windows, certainly can be
assumed to do so in coming releases; they and Hewlett-Packard collaborated on
the original sRGB proposal.








</p>


<p>But where color correction can be a little tricky, gamma correction is quite
straightforward. All one needs is the ``gamma'' value (exponent) of the
user's display system and that of the PNG file itself. If the PNG file does not include
a gAMA or sRGB chunk, there is little to be done except perhaps ask the user
for a best-guess value; a PNG decoder is likely to do more harm than good if
it attempts to guess on its own. We will simply forego any attempt at gamma
correction, in that case. But on the assumption that most PNG files will
be well behaved and include gamma information, we included the following
code at the beginning of the main program:</p>


<blockquote><pre class="code">    double LUT_exponent;
    double CRT_exponent = 2.2;
    double default_display_exponent;
  
#if defined(NeXT)
    LUT_exponent = 1.0 / 2.2;
    /*
    if (some_next_function_that_returns_gamma(&amp;next_gamma))
        LUT_exponent = 1.0 / next_gamma;
     */
#elif defined(sgi)
    LUT_exponent = 1.0 / 1.7;
    /* there doesn't seem to be any documented function to
     * get the "gamma" value, so we do it the hard way */
    infile = fopen("/etc/config/system.glGammaVal", "r");
    if (infile) {
        double sgi_gamma;
  
        fgets(fooline, 80, infile);
        fclose(infile);
        sgi_gamma = atof(fooline);
        if (sgi_gamma &gt; 0.0)
            LUT_exponent = 1.0 / sgi_gamma;
    }
#elif defined(Macintosh)
    LUT_exponent = 1.8 / 2.61;
    /*
    if (some_mac_function_that_returns_gamma(&amp;mac_gamma))
        LUT_exponent = mac_gamma / 2.61;
     */
#else
    LUT_exponent = 1.0;   /* assume no LUT:  most PCs */
#endif
  
    default_display_exponent = LUT_exponent * CRT_exponent;</pre></blockquote>


<p>The goal here is to make a reasonably well informed guess as to the overall
display system's exponent (``gamma''), which, as you'll recall from <a href="chapter10.html">Chapter 10, "Gamma Correction and Precision Color"</a>,
is the product of the lookup table's exponent and that of the monitor. Essentially all monitors have an exponent of 2.2,
so I've assumed that throughout. And almost all PCs and many workstations
forego the lookup table (LUT), effectively giving them a LUT exponent of 1.0;
the result is that their overall display-system exponent is 2.2. This is
reflected by the last line in the ifdef block.</p>


<p>A few well-known systems have LUT exponents quite different from 1.0.
The most extreme of these is the NeXT cube (and subsequent noncubic models),
which has a lookup table with a 1/2.2 exponent, resulting
in an overall exponent of 1.0 (i.e., it has a ``linear transfer function'').
Although some third-party utilities can modify the lookup table
(with a ``gamma'' value whose inverse is the LUT exponent, as on SGI systems),
there appears to be no system facility to do so and no portable method of
determining what value a third-party panel might have loaded. So we assume
1.0 in all cases when the NeXT-specific macro <b class="emphasis-bold">NeXT</b> is defined.</p>


<p>Silicon Graphics workstations and Macintoshes also have nonidentity lookup
tables, but in both cases the LUT exponent can be varied by system utilities.
Unfortunately, in both cases the value is varied via a parameter called
``gamma'' that matches neither the LUT exponent nor the other system's usage.
On SGI machines, the ``gamma'' value is the inverse of the LUT exponent (as
on the NeXT) and can be obtained either via a command (<b class="emphasis-bold">gamma</b>) or from
a system configuration file (<em class="emphasis">/etc/config/system.glGammaVal</em>); there is
no documented method to retrieve the value directly via a system function call.
Here we have used the file-based method. If we read it successfully, the
overall system exponent is calculated accordingly; if not, we assume the
default value used on factory-shipped SGI systems:  ``gamma'' of 1.7, which
implies a display-system exponent of 2.2/1.7, or 1.3. Note, however, that
what is being determined is the exponent of the console attached to the system
running the program, not necessarily that of the actual display. That
is, X programs can display on remote systems, and the exponent of the remote
display system might be anything. One could attempt to determine whether the
display is local by checking the <b class="emphasis-bold">DISPLAY</b> environment variable, but to
do so correctly could involve several system calls (<b class="emphasis-bold">uname()</b>,
<b class="emphasis-bold">gethostbyname()</b>, etc.) and is beyond the scope of this demo program.
A user-level work-around is to set the <b class="emphasis-bold">SCREEN_GAMMA</b> variable
appropriately; I'll describe that in just a moment.</p>


<p>The Macintosh ``gamma'' value is proportional to the LUT exponent, but it
is multiplied by an additional constant factor of 2.61. The default gamma
is 1.8, leading to an overall exponent of (1.8/2.61)&nbsp;&times; 2.2, or 1.5.
Since neither of the two front ends (X or Windows) is designed to work
on a Mac, the code inside the Macintosh if-def (and the <b class="emphasis-bold">Macintosh</b>
macro itself) is intended for illustration only, not as a serious example of
ready-to-compile code. Indeed, a standard component of Mac OS 8.5 is Apple's
ColorSync color management system (also available as an add-on for earlier
systems), which is the recommended way to handle both gamma and color
correction on Macs.




























</p>


<p>It is entirely possible that the user has calibrated the display system
more precisely than is reflected in the preceding code, or perhaps has a system
unlike any of the ones we have described. The main program also gives the
user the option of specifying the display system's exponent directly, either
with an environment variable (<b class="emphasis-bold">SCREEN_GAMMA</b> is suggested by the
libpng documentation) or by direct input. For the latter, we have once
again resorted to the simple expedient of a command-line option, but a more
elegant program might pop up a dialog box of some sort, or even provide a
calibration screen. In any case, our main program first checks for the
environment variable:</p>


<blockquote><pre class="code">    if ((p = getenv("SCREEN_GAMMA")) != NULL)
        display_exponent = atof(p);
    else
        display_exponent = default_display_exponent;</pre></blockquote>


<p>If the variable is found, it is used; otherwise, the previously calculated
default exponent is used. Then the program processes the command-line options
and, if the <b class="emphasis-bold">-gamma</b> option is found, its argument replaces all previously obtained values.</p>


<p>That turned out to be a moderately lengthy explanation of the demo program's
approach to gamma correction (or, more specifically, to finding the correct
value for the display system's exponent), mostly because of all the
different ways the value can be found: system-specific educated guesses at
the time of compilation, system-specific files or API calls at runtime, an
environment variable, or direct user input. The actual code is only about
20 lines long.</p>


















</div>
<div class="sect1"><a name="png.ch13.div.7" />
<h2 class="sect1">13.7. readpng_get_image()</h2>


<p>Once the display-system exponent is found, it is passed to the <b class="emphasis-bold">readpng</b>
code as the first argument to <b class="emphasis-bold">readpng_get_image()</b>:</p>


<blockquote><pre class="code">uch *readpng_get_image(double display_exponent, int *pChannels,
                       ulg *pRowbytes)</pre></blockquote>


<p>As with the previous two <b class="emphasis-bold">readpng</b> routines, <b class="emphasis-bold">readpng_get_image()</b> first
installs the libpng error-handler code (<b class="emphasis-bold">setjmp()</b>). It then sets up
all of the transformations that correspond to the design decisions described
earlier, starting with these three:</p>


<blockquote><pre class="code">    if (color_type == PNG_COLOR_TYPE_PALETTE)
        png_set_expand(png_ptr);
    if (color_type == PNG_COLOR_TYPE_GRAY &amp;&amp; bit_depth &lt; 8)
        png_set_expand(png_ptr);
    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
        png_set_expand(png_ptr);</pre></blockquote>


<p>The astute reader will have noticed something odd in the first block: the
same function, <b class="emphasis-bold">png_set_expand()</b>, is called several times, in different
contexts but with identical arguments. Indeed, this is perhaps the single
most confusing issue in all versions of libpng up through 1.0.3. In the first
case, <b class="emphasis-bold">png_set_expand()</b> is used to set a flag that will force palette
images to be expanded to 24-bit RGB. In the second case, it indicates that
low-bit-depth grayscale images are to be expanded to 8 bits. And in the
third case, the function is used to expand any tRNS chunk data into a full
alpha channel. Note that the third case can apply to either of the first
two, as well. That is, either a palette image or a grayscale image may
have a transparency chunk; in each case, <b class="emphasis-bold">png_set_expand()</b> would be
called twice in succession, for different purposes (though with the same
effect--the function merely sets a flag, independent of context). A less
confusing approach would be to create separate functions for each purpose:</p>


<blockquote><pre class="code">    /* These functions are FICTITIOUS!  They DO NOT EXIST in any
     * version of libpng to date (through 1.0.3). */

    if (color_type == PNG_COLOR_TYPE_PALETTE)
        png_set_palette_to_rgb(png_ptr);
    if (color_type == PNG_COLOR_TYPE_GRAY &amp;&amp; bit_depth &lt; 8)
        png_set_gray_1_2_4_to_8(png_ptr);
    if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
        png_set_tRNS_to_alpha(png_ptr);</pre></blockquote>


<p>With luck, these functions will be accepted for libpng version 1.0.4 (and
later).</p>


<a name="INDEX-1046.01-new" />
<p>Getting back to the real code, the next pair of transformations involves
calls to two new functions, one to reduce images with 16-bit samples
(e.g., 48-bit RGB) to 8 bits per sample and one to expand grayscale
images to RGB. Fortunately these are appropriately named:</p>


<blockquote><pre class="code">    if (bit_depth == 16)
        png_set_strip_16(png_ptr);
    if (color_type == PNG_COLOR_TYPE_GRAY ||
        color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
        png_set_gray_to_rgb(png_ptr);</pre></blockquote>


<p>The final transformation sets up the gamma-correction code, but only if the
file contains gamma information itself:</p>


<blockquote><pre class="code">    double  gamma;
  
    if (png_get_gAMA(png_ptr, info_ptr, &amp;gamma))
        png_set_gamma(png_ptr, display_exponent, gamma);</pre></blockquote>


<p>Once again, the declaration of <b class="emphasis-bold">gamma</b> is included here for context;
it actually occurs at the beginning of the function. The conditional
approach toward gamma correction is on the assumption that guessing
incorrectly is more harmful than doing no correction at all; alternatively,
the user could be queried for a best-guess value. This approach was chosen
because a simple viewer such as we describe here is probably more likely to
be used for images created on the local system than for images coming from
other systems, for which a web browser might be the usual viewer. An
alternate approach, espoused by drafts of the sRGB specification, is to
assume that all unlabeled images exist in the sRGB
space, which effectively gives them gamma values of 0.45455. On a PC-like
system with no lookup table, the two approaches amount to the same thing:
multiply the image's gamma of 0.45455 by the display-system exponent of 2.2,
and you get an overall exponent of 1.0--i.e., no correction is necessary.
But on a Macintosh, SGI, or NeXT system, the sRGB recommendation would result
in additional processing that would tend to darken images. This would
effectively favor images created on PCs over (unlabeled) images created
on the local system. The upshot is that one is making assumptions either
way; which approach is more acceptable is likely to be a matter of personal
taste. Note that the PNG 1.1 Specification recommends that the viewer
``choose a likely default gamma value, but allow the user to select a new
one if the result proves too dark or too light.''




</p>


<p>In any case, once we've registered all of our desired transformations, we
request that libpng update the information struct appropriately via the
<b class="emphasis-bold">png_read_update_info()</b> function. Then we get the values for the
number of channels and the size of each row in the image, allocate memory
for the main image buffer, and set up an array of pointers:</p>


<blockquote><pre class="code">    png_uint_32  i, rowbytes;
    png_bytep  row_pointers[height];
  
    png_read_update_info(png_ptr, info_ptr);
  
    *pRowbytes = rowbytes = png_get_rowbytes(png_ptr, info_ptr);
    *pChannels = (int)png_get_channels(png_ptr, info_ptr);
  
    if ((image_data = (uch *)malloc(rowbytes*height)) == NULL) {
        png_destroy_read_struct(&amp;png_ptr, &amp;info_ptr, NULL);
        return NULL;
    }
  
    for (i = 0;  i &lt; height;  ++i)
        row_pointers[i] = image_data + i*rowbytes;</pre></blockquote>


<p>The only slightly strange feature here is the <b class="emphasis-bold">row_pointers[]</b> array,
which is something libpng needs for its processing. In this program, where
we have allocated one big block for the image, the array is somewhat
unnecessary; libpng could just take a pointer to <b class="emphasis-bold">image_data</b> and
calculate the row offsets itself. But the row-pointers approach offers
the programmer the freedom to do things like setting up the image for
line doubling (by incrementing each row pointer by <b class="emphasis-bold">2*rowbytes</b>) or
even eliminating the <b class="emphasis-bold">image_data</b> array entirely in favor of per-row
progressive processing on a single row buffer. Of course, it is also quite
a convenient way to deal with reading and displaying the image.</p>


<p>In fact, that was the last of the preprocessing to be done. The next
step is to go ahead and read the entire image into the array we just
allocated:</p>


<blockquote><pre class="code">    png_read_image(png_ptr, row_pointers);</pre></blockquote>


<p>The <b class="emphasis-bold">readpng</b> routine can return at this point, but we added one final libpng
call for completeness. <b class="emphasis-bold">png_read_end()</b> checks the remainder of the
image for correctness and optionally reads the contents of any chunks
appearing after the IDATs (typically tEXt or tIME) into the indicated information
struct. If one has no need for the post-IDAT chunk data, as in our case,
the second argument can be NULL:</p>


<blockquote><pre class="code">    png_read_end(png_ptr, NULL);
  
    return image_data;</pre></blockquote>


<p>
<a name="INDEX-1047" />
<a name="INDEX-1048" />
<a name="INDEX-1049" />
<a name="INDEX-1050" />
</p>


















</div>
<div class="sect1"><a name="png.ch13.div.8" />
<h2 class="sect1">13.8. readpng_cleanup()</h2>


<p><a name="INDEX-1051" />
<a name="INDEX-1052" />With that, <b class="emphasis-bold">readpng_get_image()</b> returns control to our main program,
which closes the input file and promptly calls another <b class="emphasis-bold">readpng</b> routine to
clean up all allocated memory (except for the image data itself, of course):</p>


<blockquote><pre class="code">void readpng_cleanup(int free_image_data)
{
    if (free_image_data &amp;&amp; image_data) {
        free(image_data);
        image_data = NULL;
    }
  
    if (png_ptr &amp;&amp; info_ptr) {
        png_destroy_read_struct(&amp;png_ptr, &amp;info_ptr, NULL);
        png_ptr = NULL;
        info_ptr = NULL;
    }
}</pre></blockquote>


<p>That is, the main program calls <b class="emphasis-bold">readpng_cleanup()</b> with a
zero (FALSE) argument here so that <b class="emphasis-bold">image_data</b> is not freed.
If it had waited to clean up until after the user requested the program to
end, it would have passed a nonzero (TRUE) argument instead. Setting
<b class="emphasis-bold">png_ptr</b> and <b class="emphasis-bold">info_ptr</b> to NULL is unnecessary here, since
<b class="emphasis-bold">png_destroy_read_struct()</b> does that for us; but we do it anyway,
since it's a habit that tends to save on debugging time in the long run.</p>


















</div>
<div class="sect1"><a name="png.ch13.div.9" />
<h2 class="sect1">13.9. Compositing and Displaying the Image</h2>


<p><a name="INDEX-1053" />
<a name="INDEX-1054" />What one does at this point is, of course, entirely application-specific.
Our main program calls a display routine that simply puts the pixels on
the screen, first compositing against the desired background color if the 
final image has four channels (i.e., if it includes an alpha channel).
Then it waits for the user to quit the program, at which point it destroys
the window, frees any allocated memory, and exits.</p>


<p><a name="INDEX-1054.01-new" />
<p>The compositing step is perhaps interesting; it employs a macro
copied from the <em class="emphasis">png.h</em> header file, albeit renamed to avoid problems,
should <em class="emphasis">png.h</em> ever be included in the main program file, and using
equivalent typedefs:</p>


<blockquote>
<pre class="code">#define alpha_composite(composite, fg, alpha, bg) {              \
    ush temp = ((ush)(fg)*(ush)(alpha) +                         \
                (ush)(bg)*(ush)(255 - (ush)(alpha)) + (ush)128); \
    (composite) = (uch)((temp + (temp &gt;&gt; 8)) &gt;&gt; 8);              \
}</pre>
</blockquote>


<p><a name="INDEX-1054.02-new" />
<p>The unique thing about this macro is that it does <em class="emphasis">exact</em> alpha blending
on 8-bit samples (for example, the red components of a foreground pixel and a
background pixel) without performing any division. This macro and its 16-bit-per-sample
sibling have been tested on a number of PC and workstation architectures and
found to be anywhere from 2 to 13 times faster than the standard
approach, which divides by 255 or 65,535, depending on sample size. Of course,
hardware-assisted alpha compositing will always be faster than doing it in
software; many 3D accelerator cards provide this function, and often they can
be used even in 2D applications. Approximate methods (which divide by
256 of 65,536 by bit-shifting) are another fast alternative when
absolute accuracy is not important, but note that such an approach may
leave a visible border between opaque and slightly transparent regions.</p>


















</div>
<div class="sect1"><a name="png.ch13.div.10" />
<h2 class="sect1">13.10. Getting the Source Code</h2>


<p><a name="INDEX-1055" />
All of the source files for the <em class="emphasis">rpng</em> demo program
(<em class="emphasis">rpng-x.c</em>, <em class="emphasis">rpng-win.c</em>, <em class="emphasis">readpng.c</em>, <em class="emphasis">readpng.h</em>,
and makefiles) are available both in print and electronically, under a
BSD-like Open Source license. The files will be available for download
from the following URL for the foreseeable future:</p>

<blockquote>
<pre class="code"><a href="http://www.libpng.org/pub/png/pngbook.html">http://www.libpng.org/pub/png/pngbook.html</a></pre>
</blockquote>

<p>Bug fixes, new features and ports, and other contributions may be integrated
into the code, time permitting.</p>

<p><a name="INDEX-1055.01-new" />
libpng source code is available from the following URLs:</p>

<blockquote>
<pre class="code"><a href="http://www.libpng.org/pub/png/libpng.html">http://www.libpng.org/pub/png/libpng.html</a>
<a href="http://libpng.sourceforge.net/">http://libpng.sourceforge.net/</a></pre>
</blockquote>

<p><a name="INDEX-1055.02-new" />
zlib source code is available from the following site:</p>

<blockquote>
<pre class="code"><a href="http://www.zlib.org/">http://www.zlib.org/</a></pre>
</blockquote>







</div>
<div class="sect1"><a name="png.ch13.div.11" />
<h2 class="sect1">13.11. Alternative Approaches</h2>


<p><a name="INDEX-1056" />It should go without saying that the program presented here is among the
simplest of many possibilities. It would also have been possible to write
it monolithically, either as a single <b class="emphasis-bold">readpng</b> function or even as inlined
code within <b class="emphasis-bold">main()</b>, which is precisely how the sample code
in the libpng documentation reads. Libpng allows user-defined I/O routines
<a name="INDEX-1057" />
<a name="INDEX-1058" />
<a name="INDEX-1059" />(in place of standard file I/O), custom memory allocators, and alternate error
handlers to be installed, although there is currently no provision for an
error-handling function that returns control to the libpng routine that called
it.
<a name="INDEX-1060" />
<a name="INDEX-1061" /></p>


<p>There are also other options for the platform-dependent front ends, of
course; reading an image from a file is often undesirable. One method
in particular is worth mentioning, since it does not appear to be documented
anywhere else at the time of this writing. On the 32-bit Windows platform, a
<a name="INDEX-1062" />``private'' clipboard may be used to transfer PNG images between applications.
The data format is simply the normal PNG stream, beginning with the signature
bytes and ending with the IEND chunk. An application like <em class="emphasis">rpng-win</em>
would register the private clipboard and then read PNG data from it in the
usual way. The following code fragment outlines the essential steps:</p>


<blockquote>
<pre class="code">    UINT clipbd_format = RegisterClipboardFormat("PNG");
  
    if (clipbd_format == 0) {
        /* call failed:  use GetLastError() for extended info */
    } else if (OpenClipboard(NULL)) {
        HANDLE handle = GetClipboardData(clipbd_format);
  
        if (handle == NULL) {
            /* call failed:  use GetLastError() for info */
        } else {
            int data_length = GlobalSize(handle);   /* upper bound */
  
            if (data_length == 0) {
                /* call failed:  use GetLastError() for info */
            } else {
                BYTE *data_ptr = GlobalLock(handle);

                if (data_ptr == NULL) {
                    /* call failed:  use GetLastError() for info */
                } else {

                    /*================================================*/
                    /* copy PNG data immediately, but don't flag an   */
                    /* error if there are some extra bytes after IEND */
                    /*================================================*/

                    if (GlobalUnlock(handle) == 0) {
                        /* call failed:  use GetLastError() for info */
                    }
                }
            }
        }
        if (CloseClipboard()) {
            /* call failed:  use GetLastError() for info */
        }
    } else {
        /* another window has the clipboard open */
        /* (can use GetOpenClipboardWindow() to get handle to it) */
    }</pre>
</blockquote>


<p>
That one can do something like this in principle isn't new or unusual;
what is new is that the <b class="emphasis-bold">"PNG"</b> clipboard has
already been implemented in
<a name="INDEX-1063" />
<a name="INDEX-1064" />
some Microsoft apps, including Office 2000. All any other application needs in 
order to interoperate via this clipboard is its name and data format, which 
I've just described. Thanks to John Bowler for providing this information 
to the PNG Development Group.
<a name="INDEX-1065" />
</p>


<p>
In the next chapter, I'll look at a more radical alternative to the basic PNG
decoder: a version that feeds libpng data at its own pace, rather than letting
libpng read (and possibly wait for) as much data as it wants. Progressive
viewers are at the heart of most online browsers, so we'll look at how to
write one for PNG images.
<a name="INDEX-1066" />
<a name="INDEX-1067" />
<a name="INDEX-1068" />
<a name="INDEX-1069" />
<a name="INDEX-1070" />
<a name="INDEX-1071" />
<a name="INDEX-1072" />
</p>

</div>


<hr> <!-- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -->

<a href="chapter12.html"><img width=24 height=13 border=0 align="left"
 src="images/prev.png" alt="&lt;-"></a>

<a href="chapter14.html"><img width=24 height=13 border=0 align="right"
 src="images/next.png" alt="-&gt;"></a>

<div align="center">
  <a href="chapter12.html"><font size="-1" color="#000000"
   ><b>PREVIOUS</b></font></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a
     href="toc.html"><font size="-1" color="#000000"
   ><b>CONTENTS</b></font></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a
     href="chapter14.html"><font size="-1" color="#000000"
   ><b>NEXT</b></font></a>
</div>

<hr> <!-- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -->



</body></html>