summaryrefslogtreecommitdiffstats
path: root/tk8.6/generic/tkImgPPM.c
blob: 6f084f0759219a38934c5f511c83be44fdb61abe (plain)
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
/*
 * tkImgPPM.c --
 *
 *	A photo image file handler for PPM (Portable PixMap) files.
 *
 * Copyright (c) 1994 The Australian National University.
 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * Author: Paul Mackerras (paulus@cs.anu.edu.au),
 *	Department of Computer Science,
 *	Australian National University.
 */

#include "tkInt.h"

/*
 * The maximum amount of memory to allocate for data read from the file. If we
 * need more than this, we do it in pieces.
 */

#define MAX_MEMORY	10000		/* don't allocate > 10KB */

/*
 * Define PGM and PPM, i.e. gray images and color images.
 */

#define PGM 1
#define PPM 2

/*
 * The format record for the PPM file format:
 */

static int		FileMatchPPM(Tcl_Channel chan, const char *fileName,
			    Tcl_Obj *format, int *widthPtr, int *heightPtr,
			    Tcl_Interp *interp);
static int		FileReadPPM(Tcl_Interp *interp, Tcl_Channel chan,
			    const char *fileName, Tcl_Obj *format,
			    Tk_PhotoHandle imageHandle, int destX, int destY,
			    int width, int height, int srcX, int srcY);
static int		FileWritePPM(Tcl_Interp *interp, const char *fileName,
			    Tcl_Obj *format, Tk_PhotoImageBlock *blockPtr);
static int		StringWritePPM(Tcl_Interp *interp, Tcl_Obj *format,
			    Tk_PhotoImageBlock *blockPtr);
static int		StringMatchPPM(Tcl_Obj *dataObj, Tcl_Obj *format,
			    int *widthPtr, int *heightPtr, Tcl_Interp *interp);
static int		StringReadPPM(Tcl_Interp *interp, Tcl_Obj *dataObj,
			    Tcl_Obj *format, Tk_PhotoHandle imageHandle,
			    int destX, int destY, int width, int height,
			    int srcX, int srcY);

Tk_PhotoImageFormat tkImgFmtPPM = {
    "ppm",			/* name */
    FileMatchPPM,		/* fileMatchProc */
    StringMatchPPM,		/* stringMatchProc */
    FileReadPPM,		/* fileReadProc */
    StringReadPPM,		/* stringReadProc */
    FileWritePPM,		/* fileWriteProc */
    StringWritePPM,		/* stringWriteProc */
    NULL
};

/*
 * Prototypes for local functions defined in this file:
 */

static int		ReadPPMFileHeader(Tcl_Channel chan, int *widthPtr,
			    int *heightPtr, int *maxIntensityPtr);
static int		ReadPPMStringHeader(Tcl_Obj *dataObj, int *widthPtr,
			    int *heightPtr, int *maxIntensityPtr,
			    unsigned char **dataBufferPtr, int *dataSizePtr);

/*
 *----------------------------------------------------------------------
 *
 * FileMatchPPM --
 *
 *	This function is invoked by the photo image type to see if a file
 *	contains image data in PPM format.
 *
 * Results:
 *	The return value is >0 if the first characters in file "f" look like
 *	PPM data, and 0 otherwise.
 *
 * Side effects:
 *	The access position in f may change.
 *
 *----------------------------------------------------------------------
 */

static int
FileMatchPPM(
    Tcl_Channel chan,		/* The image file, open for reading. */
    const char *fileName,	/* The name of the image file. */
    Tcl_Obj *format,		/* User-specified format string, or NULL. */
    int *widthPtr, int *heightPtr,
				/* The dimensions of the image are returned
				 * here if the file is a valid raw PPM
				 * file. */
    Tcl_Interp *interp)		/* unused */
{
    int dummy;

    return ReadPPMFileHeader(chan, widthPtr, heightPtr, &dummy);
}

/*
 *----------------------------------------------------------------------
 *
 * FileReadPPM --
 *
 *	This function is called by the photo image type to read PPM format
 *	data from a file and write it into a given photo image.
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 * Side effects:
 *	The access position in file f is changed, and new data is added to the
 *	image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
FileReadPPM(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tcl_Channel chan,		/* The image file, open for reading. */
    const char *fileName,	/* The name of the image file. */
    Tcl_Obj *format,		/* User-specified format string, or NULL. */
    Tk_PhotoHandle imageHandle,	/* The photo image to write into. */
    int destX, int destY,	/* Coordinates of top-left pixel in photo
				 * image to be written to. */
    int width, int height,	/* Dimensions of block of photo image to be
				 * written to. */
    int srcX, int srcY)		/* Coordinates of top-left pixel to be used in
				 * image being read. */
{
    int fileWidth, fileHeight, maxIntensity;
    int nLines, nBytes, h, type, count, bytesPerChannel = 1;
    unsigned char *pixelPtr;
    Tk_PhotoImageBlock block;

    type = ReadPPMFileHeader(chan, &fileWidth, &fileHeight, &maxIntensity);
    if (type == 0) {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		"couldn't read raw PPM header from file \"%s\"", fileName));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "PPM", "NO_HEADER", NULL);
	return TCL_ERROR;
    }
    if ((fileWidth <= 0) || (fileHeight <= 0)) {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		"PPM image file \"%s\" has dimension(s) <= 0", fileName));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "PPM", "DIMENSIONS", NULL);
	return TCL_ERROR;
    }
    if ((maxIntensity <= 0) || (maxIntensity > 0xffff)) {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		"PPM image file \"%s\" has bad maximum intensity value %d",
		fileName, maxIntensity));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "PPM", "INTENSITY", NULL);
	return TCL_ERROR;
    } else if (maxIntensity > 0x00ff) {
	bytesPerChannel = 2;
    }

    if ((srcX + width) > fileWidth) {
	width = fileWidth - srcX;
    }
    if ((srcY + height) > fileHeight) {
	height = fileHeight - srcY;
    }
    if ((width <= 0) || (height <= 0)
	    || (srcX >= fileWidth) || (srcY >= fileHeight)) {
	return TCL_OK;
    }

    if (type == PGM) {
	block.pixelSize = 1 * bytesPerChannel;
	block.offset[0] = 0;
	block.offset[1] = 0;
	block.offset[2] = 0;
    } else {
	block.pixelSize = 3 * bytesPerChannel;
	block.offset[0] = 0;
	block.offset[1] = 1 * bytesPerChannel;
	block.offset[2] = 2 * bytesPerChannel;
    }
    block.offset[3] = 0;
    block.width = width;
    block.pitch = block.pixelSize * fileWidth;

    if (Tk_PhotoExpand(interp, imageHandle,
	    destX + width, destY + height) != TCL_OK) {
	return TCL_ERROR;
    }

    if (srcY > 0) {
	Tcl_Seek(chan, (Tcl_WideInt)(srcY * block.pitch), SEEK_CUR);
    }

    nLines = (MAX_MEMORY + block.pitch - 1) / block.pitch;
    if (nLines > height) {
	nLines = height;
    }
    if (nLines <= 0) {
	nLines = 1;
    }
    nBytes = nLines * block.pitch;
    pixelPtr = ckalloc(nBytes);
    block.pixelPtr = pixelPtr + srcX * block.pixelSize;

    for (h = height; h > 0; h -= nLines) {
	if (nLines > h) {
	    nLines = h;
	    nBytes = nLines * block.pitch;
	}
	count = Tcl_Read(chan, (char *) pixelPtr, nBytes);
	if (count != nBytes) {
	    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		    "error reading PPM image file \"%s\": %s", fileName,
		    Tcl_Eof(chan)?"not enough data":Tcl_PosixError(interp)));
	    if (Tcl_Eof(chan)) {
		Tcl_SetErrorCode(interp, "TK", "IMAGE", "PPM", "EOF", NULL);
	    }
	    ckfree(pixelPtr);
	    return TCL_ERROR;
	}
	if (maxIntensity < 0x00ff) {
	    unsigned char *p;

	    for (p = pixelPtr; count > 0; count--, p++) {
		*p = (((int) *p) * 255)/maxIntensity;
	    }
	} else if (maxIntensity > 0x00ff) {
	    unsigned char *p;
	    unsigned int value;

	    for (p = pixelPtr; count > 0; count--, p += 2) {
		value = ((unsigned int) p[0]) * 256 + ((unsigned int) p[1]);
		value = value * 255 / maxIntensity;
		p[0] = p[1] = (unsigned char) value;
	    }
	}
	block.height = nLines;
	if (Tk_PhotoPutBlock(interp, imageHandle, &block, destX, destY,
		width, nLines, TK_PHOTO_COMPOSITE_SET) != TCL_OK) {
	    ckfree(pixelPtr);
	    return TCL_ERROR;
	}
	destY += nLines;
    }

    ckfree(pixelPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * FileWritePPM --
 *
 *	This function is invoked to write image data to a file in PPM format
 *	(although we can read PGM files, we never write them).
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 * Side effects:
 *	Data is written to the file given by "fileName".
 *
 *----------------------------------------------------------------------
 */

static int
FileWritePPM(
    Tcl_Interp *interp,
    const char *fileName,
    Tcl_Obj *format,
    Tk_PhotoImageBlock *blockPtr)
{
    Tcl_Channel chan;
    int w, h, greenOffset, blueOffset, nBytes;
    unsigned char *pixelPtr, *pixLinePtr;
    char header[16 + TCL_INTEGER_SPACE * 2];

    chan = Tcl_OpenFileChannel(interp, fileName, "w", 0666);
    if (chan == NULL) {
	return TCL_ERROR;
    }

    if (Tcl_SetChannelOption(interp, chan, "-translation", "binary")
	    != TCL_OK) {
	Tcl_Close(NULL, chan);
	return TCL_ERROR;
    }
    if (Tcl_SetChannelOption(interp, chan, "-encoding", "binary")
	    != TCL_OK) {
	Tcl_Close(NULL, chan);
	return TCL_ERROR;
    }

    sprintf(header, "P6\n%d %d\n255\n", blockPtr->width, blockPtr->height);
    Tcl_Write(chan, header, -1);

    pixLinePtr = blockPtr->pixelPtr + blockPtr->offset[0];
    greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
    blueOffset = blockPtr->offset[2] - blockPtr->offset[0];

    if ((greenOffset == 1) && (blueOffset == 2) && (blockPtr->pixelSize == 3)
	    && (blockPtr->pitch == (blockPtr->width * 3))) {
	nBytes = blockPtr->height * blockPtr->pitch;
	if (Tcl_Write(chan, (char *) pixLinePtr, nBytes) != nBytes) {
	    goto writeerror;
	}
    } else {
	for (h = blockPtr->height; h > 0; h--) {
	    pixelPtr = pixLinePtr;
	    for (w = blockPtr->width; w > 0; w--) {
		if (    Tcl_Write(chan,(char *)&pixelPtr[0], 1) == -1 ||
			Tcl_Write(chan,(char *)&pixelPtr[greenOffset],1)==-1 ||
			Tcl_Write(chan,(char *)&pixelPtr[blueOffset],1) ==-1) {
		    goto writeerror;
		}
		pixelPtr += blockPtr->pixelSize;
	    }
	    pixLinePtr += blockPtr->pitch;
	}
    }

    if (Tcl_Close(NULL, chan) == 0) {
	return TCL_OK;
    }
    chan = NULL;

  writeerror:
    Tcl_SetObjResult(interp, Tcl_ObjPrintf("error writing \"%s\": %s",
	    fileName, Tcl_PosixError(interp)));
    if (chan != NULL) {
	Tcl_Close(NULL, chan);
    }
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * StringWritePPM --
 *
 *	This function is invoked to write image data to a string in PPM
 *	format.
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

static int
StringWritePPM(
    Tcl_Interp *interp,
    Tcl_Obj *format,
    Tk_PhotoImageBlock *blockPtr)
{
    int w, h, size, greenOffset, blueOffset;
    unsigned char *pixLinePtr, *byteArray;
    char header[16 + TCL_INTEGER_SPACE * 2];
    Tcl_Obj *byteArrayObj;

    sprintf(header, "P6\n%d %d\n255\n", blockPtr->width, blockPtr->height);

    /*
     * Construct a byte array of the right size with the header and
     * get a pointer to the data part of it.
     */

    size = strlen(header);
    byteArrayObj = Tcl_NewByteArrayObj((unsigned char *)header, size);
    byteArray = Tcl_SetByteArrayLength(byteArrayObj,
	    size + 3*blockPtr->width*blockPtr->height);
    byteArray += size;

    pixLinePtr = blockPtr->pixelPtr + blockPtr->offset[0];
    greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
    blueOffset = blockPtr->offset[2] - blockPtr->offset[0];

    /*
     * Check if we can do the data move in single action.
     */

    if ((greenOffset == 1) && (blueOffset == 2) && (blockPtr->pixelSize == 3)
	    && (blockPtr->pitch == (blockPtr->width * 3))) {
	memcpy(byteArray, pixLinePtr,
		(unsigned)blockPtr->height * blockPtr->pitch);
    } else {
	for (h = blockPtr->height; h > 0; h--) {
	    unsigned char *pixelPtr = pixLinePtr;

	    for (w = blockPtr->width; w > 0; w--) {
		*byteArray++ = pixelPtr[0];
		*byteArray++ = pixelPtr[greenOffset];
		*byteArray++ = pixelPtr[blueOffset];
		pixelPtr += blockPtr->pixelSize;
	    }
	    pixLinePtr += blockPtr->pitch;
	}
    }

    /*
     * Return the object in the interpreter result.
     */

    Tcl_SetObjResult(interp, byteArrayObj);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringMatchPPM --
 *
 *	This function is invoked by the photo image type to see if a string
 *	contains image data in PPM format.
 *
 * Results:
 *	The return value is >0 if the first characters in file "f" look like
 *	PPM data, and 0 otherwise.
 *
 * Side effects:
 *	The access position in f may change.
 *
 *----------------------------------------------------------------------
 */

static int
StringMatchPPM(
    Tcl_Obj *dataObj,		/* The image data. */
    Tcl_Obj *format,		/* User-specified format string, or NULL. */
    int *widthPtr, int *heightPtr,
				/* The dimensions of the image are returned
				 * here if the file is a valid raw PPM
				 * file. */
    Tcl_Interp *interp)		/* unused */
{
    int dummy;

    return ReadPPMStringHeader(dataObj, widthPtr, heightPtr,
	    &dummy, NULL, NULL);
}

/*
 *----------------------------------------------------------------------
 *
 * StringReadPPM --
 *
 *	This function is called by the photo image type to read PPM format
 *	data from a string and write it into a given photo image.
 *
 * Results:
 *	A standard TCL completion code. If TCL_ERROR is returned then an error
 *	message is left in the interp's result.
 *
 * Side effects:
 *	New data is added to the image given by imageHandle.
 *
 *----------------------------------------------------------------------
 */

static int
StringReadPPM(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tcl_Obj *dataObj,		/* The image data. */
    Tcl_Obj *format,		/* User-specified format string, or NULL. */
    Tk_PhotoHandle imageHandle,	/* The photo image to write into. */
    int destX, int destY,	/* Coordinates of top-left pixel in photo
				 * image to be written to. */
    int width, int height,	/* Dimensions of block of photo image to be
				 * written to. */
    int srcX, int srcY)		/* Coordinates of top-left pixel to be used in
				 * image being read. */
{
    int fileWidth, fileHeight, maxIntensity;
    int nLines, nBytes, h, type, count, dataSize, bytesPerChannel = 1;
    unsigned char *pixelPtr, *dataBuffer;
    Tk_PhotoImageBlock block;

    type = ReadPPMStringHeader(dataObj, &fileWidth, &fileHeight,
	    &maxIntensity, &dataBuffer, &dataSize);
    if (type == 0) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj(
		"couldn't read raw PPM header from string", -1));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "PPM", "NO_HEADER", NULL);
	return TCL_ERROR;
    }
    if ((fileWidth <= 0) || (fileHeight <= 0)) {
	Tcl_SetObjResult(interp, Tcl_NewStringObj(
		"PPM image data has dimension(s) <= 0", -1));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "PPM", "DIMENSIONS", NULL);
	return TCL_ERROR;
    }
    if ((maxIntensity <= 0) || (maxIntensity > 0xffff)) {
	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
		"PPM image data has bad maximum intensity value %d",
		maxIntensity));
	Tcl_SetErrorCode(interp, "TK", "IMAGE", "PPM", "INTENSITY", NULL);
	return TCL_ERROR;
    } else if (maxIntensity > 0x00ff) {
	bytesPerChannel = 2;
    }

    if ((srcX + width) > fileWidth) {
	width = fileWidth - srcX;
    }
    if ((srcY + height) > fileHeight) {
	height = fileHeight - srcY;
    }
    if ((width <= 0) || (height <= 0)
	|| (srcX >= fileWidth) || (srcY >= fileHeight)) {
	return TCL_OK;
    }

    if (type == PGM) {
	block.pixelSize = 1 * bytesPerChannel;
	block.offset[0] = 0;
	block.offset[1] = 0;
	block.offset[2] = 0;
    } else {
	block.pixelSize = 3 * bytesPerChannel;
	block.offset[0] = 0;
	block.offset[1] = 1 * bytesPerChannel;
	block.offset[2] = 2 * bytesPerChannel;
    }
    block.offset[3] = 0;
    block.width = width;
    block.pitch = block.pixelSize * fileWidth;

    if (srcY > 0) {
	dataBuffer += srcY * block.pitch;
	dataSize -= srcY * block.pitch;
    }

    if (maxIntensity == 0x00ff) {
	/*
	 * We have all the data in memory, so write everything in one go.
	 */

	if (block.pitch*height > dataSize) {
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "truncated PPM data", -1));
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PPM", "TRUNCATED", NULL);
	    return TCL_ERROR;
	}
	block.pixelPtr = dataBuffer + srcX * block.pixelSize;
	block.height = height;
	return Tk_PhotoPutBlock(interp, imageHandle, &block, destX, destY,
		width, height, TK_PHOTO_COMPOSITE_SET);
    }

    if (Tk_PhotoExpand(interp, imageHandle,
	    destX + width, destY + height) != TCL_OK) {
	return TCL_ERROR;
    }

    nLines = (MAX_MEMORY + block.pitch - 1) / block.pitch;
    if (nLines > height) {
	nLines = height;
    }
    if (nLines <= 0) {
	nLines = 1;
    }
    nBytes = nLines * block.pitch;
    pixelPtr = ckalloc(nBytes);
    block.pixelPtr = pixelPtr + srcX * block.pixelSize;

    for (h = height; h > 0; h -= nLines) {
	unsigned char *p;

	if (nLines > h) {
	    nLines = h;
	    nBytes = nLines * block.pitch;
	}
	if (dataSize < nBytes) {
	    ckfree(pixelPtr);
	    Tcl_SetObjResult(interp, Tcl_NewStringObj(
		    "truncated PPM data", -1));
	    Tcl_SetErrorCode(interp, "TK", "IMAGE", "PPM", "TRUNCATED", NULL);
	    return TCL_ERROR;
	}
	if (maxIntensity < 0x00ff) {
	    for (p=pixelPtr,count=nBytes ; count>0 ; count--,p++,dataBuffer++) {
		*p = (((int) *dataBuffer) * 255)/maxIntensity;
	    }
	} else {
	    unsigned char *p;
	    unsigned int value;

	    for (p = pixelPtr,count=nBytes; count > 1; count-=2, p += 2) {
		value = ((unsigned int) p[0]) * 256 + ((unsigned int) p[1]);
		value = value * 255 / maxIntensity;
		p[0] = p[1] = (unsigned char) value;
	    }
	}
	dataSize -= nBytes;
	block.height = nLines;
	if (Tk_PhotoPutBlock(interp, imageHandle, &block, destX, destY,
		width, nLines, TK_PHOTO_COMPOSITE_SET) != TCL_OK) {
	    ckfree(pixelPtr);
	    return TCL_ERROR;
	}
	destY += nLines;
    }

    ckfree(pixelPtr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * ReadPPMFileHeader --
 *
 *	This function reads the PPM header from the beginning of a PPM file
 *	and returns information from the header.
 *
 * Results:
 *	The return value is PGM if file "f" appears to start with a valid PGM
 *	header, PPM if "f" appears to start with a valid PPM header, and 0
 *	otherwise. If the header is valid, then *widthPtr and *heightPtr are
 *	modified to hold the dimensions of the image and *maxIntensityPtr is
 *	modified to hold the value of a "fully on" intensity value.
 *
 * Side effects:
 *	The access position in f advances.
 *
 *----------------------------------------------------------------------
 */

static int
ReadPPMFileHeader(
    Tcl_Channel chan,		/* Image file to read the header from. */
    int *widthPtr, int *heightPtr,
				/* The dimensions of the image are returned
				 * here. */
    int *maxIntensityPtr)	/* The maximum intensity value for the image
				 * is stored here. */
{
#define BUFFER_SIZE 1000
    char buffer[BUFFER_SIZE], c;
    int i, numFields, type = 0;

    /*
     * Read 4 space-separated fields from the file, ignoring comments (any
     * line that starts with "#").
     */

    if (Tcl_Read(chan, &c, 1) != 1) {
	return 0;
    }
    i = 0;
    for (numFields = 0; numFields < 4; numFields++) {
	/*
	 * Skip comments and white space.
	 */

	while (1) {
	    while (isspace(UCHAR(c))) {
		if (Tcl_Read(chan, &c, 1) != 1) {
		    return 0;
		}
	    }
	    if (c != '#') {
		break;
	    }
	    do {
		if (Tcl_Read(chan, &c, 1) != 1) {
		    return 0;
		}
	    } while (c != '\n');
	}

	/*
	 * Read a field (everything up to the next white space).
	 */

	while (!isspace(UCHAR(c))) {
	    if (i < (BUFFER_SIZE-2)) {
		buffer[i] = c;
		i++;
	    }
	    if (Tcl_Read(chan, &c, 1) != 1) {
		goto done;
	    }
	}
	if (i < (BUFFER_SIZE-1)) {
	    buffer[i] = ' ';
	    i++;
	}
    }

  done:
    buffer[i] = 0;

    /*
     * Parse the fields, which are: id, width, height, maxIntensity.
     */

    if (strncmp(buffer, "P6 ", 3) == 0) {
	type = PPM;
    } else if (strncmp(buffer, "P5 ", 3) == 0) {
	type = PGM;
    } else {
	return 0;
    }
    if (sscanf(buffer+3, "%d %d %d", widthPtr, heightPtr, maxIntensityPtr)
	    != 3) {
	return 0;
    }
    return type;
}

/*
 *----------------------------------------------------------------------
 *
 * ReadPPMStringHeader --
 *
 *	This function reads the PPM header from the beginning of a PPM-format
 *	string and returns information from the header.
 *
 * Results:
 *	The return value is PGM if the string appears to start with a valid
 *	PGM header, PPM if the string appears to start with a valid PPM
 *	header, and 0 otherwise. If the header is valid, then *widthPtr and
 *	*heightPtr are modified to hold the dimensions of the image and
 *	*maxIntensityPtr is modified to hold the value of a "fully on"
 *	intensity value.
 *
 * Side effects:
 *	None
 *
 *----------------------------------------------------------------------
 */

static int
ReadPPMStringHeader(
    Tcl_Obj *dataPtr,		/* Object to read the header from. */
    int *widthPtr, int *heightPtr,
				/* The dimensions of the image are returned
				 * here. */
    int *maxIntensityPtr,	/* The maximum intensity value for the image
				 * is stored here. */
    unsigned char **dataBufferPtr,
    int *dataSizePtr)
{
#define BUFFER_SIZE 1000
    char buffer[BUFFER_SIZE], c;
    int i, numFields, dataSize, type = 0;
    unsigned char *dataBuffer;

    dataBuffer = Tcl_GetByteArrayFromObj(dataPtr, &dataSize);

    /*
     * Read 4 space-separated fields from the string, ignoring comments (any
     * line that starts with "#").
     */

    if (dataSize-- < 1) {
	return 0;
    }
    c = (char) (*dataBuffer++);
    i = 0;
    for (numFields = 0; numFields < 4; numFields++) {
	/*
	 * Skip comments and white space.
	 */

	while (1) {
	    while (isspace(UCHAR(c))) {
		if (dataSize-- < 1) {
		    return 0;
		}
		c = (char) (*dataBuffer++);
	    }
	    if (c != '#') {
		break;
	    }
	    do {
		if (dataSize-- < 1) {
		    return 0;
		}
		c = (char) (*dataBuffer++);
	    } while (c != '\n');
	}

	/*
	 * Read a field (everything up to the next white space).
	 */

	while (!isspace(UCHAR(c))) {
	    if (i < (BUFFER_SIZE-2)) {
		buffer[i] = c;
		i++;
	    }
	    if (dataSize-- < 1) {
		goto done;
	    }
	    c = (char) (*dataBuffer++);
	}
	if (i < (BUFFER_SIZE-1)) {
	    buffer[i] = ' ';
	    i++;
	}
    }

  done:
    buffer[i] = 0;

    /*
     * Parse the fields, which are: id, width, height, maxIntensity.
     */

    if (strncmp(buffer, "P6 ", 3) == 0) {
	type = PPM;
    } else if (strncmp(buffer, "P5 ", 3) == 0) {
	type = PGM;
    } else {
	return 0;
    }
    if (sscanf(buffer+3, "%d %d %d", widthPtr, heightPtr, maxIntensityPtr)
	    != 3) {
	return 0;
    }
    if (dataBufferPtr != NULL) {
	*dataBufferPtr = dataBuffer;
	*dataSizePtr = dataSize;
    }
    return type;
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */