tiff.c 45.3 KB
Newer Older
Elliot Lee's avatar
Elliot Lee committed
1
2
/* tiff loading and saving for the GIMP
 *  -Peter Mattis
Sven Neumann's avatar
Sven Neumann committed
3
4
 * The TIFF loading code has been completely revamped by Nick Lamb
 * njl195@zepler.org.uk -- 18 May 1998
5
6
 * And it now gains support for tiles (and doubtless a zillion bugs)
 * njl195@zepler.org.uk -- 12 June 1999
Elliot Lee's avatar
Elliot Lee committed
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
 * The code for this filter is based on "tifftopnm" and "pnmtotiff",
 *  2 programs that are a part of the netpbm package.
 */

/*
** tifftopnm.c - converts a Tagged Image File to a portable anymap
**
** Derived by Jef Poskanzer from tif2ras.c, which is:
**
** Copyright (c) 1990 by Sun Microsystems, Inc.
**
** Author: Patrick J. Naughton
** naughton@wind.sun.com
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation.
**
** This file is provided AS IS with no warranties of any kind.  The author
** shall have no liability with respect to the infringement of copyrights,
** trade secrets or any patents by this file or any part thereof.  In no
** event will the author be liable for any lost revenue or profits or
** other special, indirect and consequential damages.
*/

#include <stdlib.h>
#include <string.h>
#include <tiffio.h>
#include "libgimp/gimp.h"
Sven Neumann's avatar
Sven Neumann committed
38
#include "libgimp/gimpui.h"
39

Elliot Lee's avatar
Elliot Lee committed
40
41
42
43
44
45
46
47
48
49
50
typedef struct
{
  gint  compression;
  gint  fillorder;
} TiffSaveVals;

typedef struct
{
  gint  run;
} TiffSaveInterface;

51
52
53
54
55
56
57
58
typedef struct {
  gint32 ID;
  GDrawable *drawable;
  GPixelRgn pixel_rgn;
  guchar *pixels;
  guchar *pixel;
} channel_data;

Elliot Lee's avatar
Elliot Lee committed
59
60
61
62
63
64
65
66
67
/* Declare some local functions.
 */
static void   query      (void);
static void   run        (char    *name,
                          int      nparams,
                          GParam  *param,
                          int     *nreturn_vals,
                          GParam **return_vals);
static gint32 load_image (char   *filename);
68
69
70
71
72
73

static void   load_rgba  (TIFF *tif, channel_data *channel);
static void   load_lines (TIFF *tif, channel_data *channel,
                         unsigned short bps, unsigned short photomet,
                         int alpha, int extra);
static void   load_tiles (TIFF *tif, channel_data *channel,
74
                         unsigned short bps, unsigned short photomet,
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
                         int alpha, int extra);

static void   read_separate (guchar *source, channel_data *channel,
                             unsigned short bps, unsigned short photomet,
                             int startcol, int startrow, int rows, int cols,
                             int alpha, int extra, int sample);
static void   read_16bit (guchar *source, channel_data *channel,
                          unsigned short photomet,
                          int startcol, int startrow, int rows, int cols,
                          int alpha, int extra);
static void   read_8bit (guchar *source, channel_data *channel,
                         unsigned short photomet,
                         int startcol, int startrow, int rows, int cols,
                         int alpha, int extra);
static void   read_default (guchar *source, channel_data *channel,
90
                            unsigned short bps, unsigned short photomet,
91
92
93
                            int startcol, int startrow, int rows, int cols,
                            int alpha, int extra);

Elliot Lee's avatar
Elliot Lee committed
94
static gint   save_image (char   *filename,
Sven Neumann's avatar
Sven Neumann committed
95
			  gint32  image,
Sven Neumann's avatar
Sven Neumann committed
96
97
			  gint32  drawable,
			  gint32  orig_image);
Elliot Lee's avatar
Elliot Lee committed
98

Sven Neumann's avatar
Sven Neumann committed
99
static void   init_gtk ();
Elliot Lee's avatar
Elliot Lee committed
100
101
102
103
104
105
106
107
static gint   save_dialog ();

static void   save_close_callback  (GtkWidget *widget,
				    gpointer   data);
static void   save_ok_callback     (GtkWidget *widget,
				    gpointer   data);
static void   save_toggle_update   (GtkWidget *widget,
				    gpointer   data);
108
109
static void   comment_entry_callback  (GtkWidget *widget,
				       gpointer   data);
Elliot Lee's avatar
Elliot Lee committed
110

111
#define DEFAULT_COMMENT "Created with The GIMP"
Elliot Lee's avatar
Elliot Lee committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130

GPlugInInfo PLUG_IN_INFO =
{
  NULL,    /* init_proc */
  NULL,    /* quit_proc */
  query,   /* query_proc */
  run,     /* run_proc */
};

static TiffSaveVals tsvals =
{
  COMPRESSION_LZW,    /*  compression  */
};

static TiffSaveInterface tsint =
{
  FALSE                /*  run  */
};

131
static char *image_comment= NULL;
Elliot Lee's avatar
Elliot Lee committed
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

MAIN ()

static void
query ()
{
  static GParamDef load_args[] =
  {
    { PARAM_INT32, "run_mode", "Interactive, non-interactive" },
    { PARAM_STRING, "filename", "The name of the file to load" },
    { PARAM_STRING, "raw_filename", "The name of the file to load" },
  };
  static GParamDef load_return_vals[] =
  {
    { PARAM_IMAGE, "image", "Output image" },
  };
  static int nload_args = sizeof (load_args) / sizeof (load_args[0]);
  static int nload_return_vals = sizeof (load_return_vals) / sizeof (load_return_vals[0]);

  static GParamDef save_args[] =
  {
    { PARAM_INT32, "run_mode", "Interactive, non-interactive" },
    { PARAM_IMAGE, "image", "Input image" },
    { PARAM_DRAWABLE, "drawable", "Drawable to save" },
    { PARAM_STRING, "filename", "The name of the file to save the image in" },
    { PARAM_STRING, "raw_filename", "The name of the file to save the image in" },
158
    { PARAM_INT32, "compression", "Compression type: { NONE (0), LZW (1), PACKBITS (2)" },
Elliot Lee's avatar
Elliot Lee committed
159
160
161
162
163
164
  };
  static int nsave_args = sizeof (save_args) / sizeof (save_args[0]);

  gimp_install_procedure ("file_tiff_load",
                          "loads files of the tiff file format",
                          "FIXME: write help for tiff_load",
Sven Neumann's avatar
Sven Neumann committed
165
                          "Spencer Kimball, Peter Mattis & Nick Lamb",
Manish Singh's avatar
Manish Singh committed
166
                          "Nick Lamb <njl195@zepler.org.uk>",
167
                          "1995-1996,1998-1999",
Elliot Lee's avatar
Elliot Lee committed
168
169
170
171
172
173
174
175
176
177
178
179
180
                          "<Load>/Tiff",
			  NULL,
                          PROC_PLUG_IN,
                          nload_args, nload_return_vals,
                          load_args, load_return_vals);

  gimp_install_procedure ("file_tiff_save",
                          "saves files in the tiff file format",
                          "FIXME: write help for tiff_save",
                          "Spencer Kimball & Peter Mattis",
                          "Spencer Kimball & Peter Mattis",
                          "1995-1996",
                          "<Save>/Tiff",
Sven Neumann's avatar
Sven Neumann committed
181
			  "RGB*, GRAY*, INDEXED",
Elliot Lee's avatar
Elliot Lee committed
182
183
184
185
186
187
188
189
190
                          PROC_PLUG_IN,
                          nsave_args, 0,
                          save_args, NULL);

  gimp_register_magic_load_handler ("file_tiff_load", "tif,tiff", "",
             "0,string,II*\\0,0,string,MM\\0*");
  gimp_register_save_handler ("file_tiff_save", "tif,tiff", "");
}

191
192
193



Elliot Lee's avatar
Elliot Lee committed
194
195
196
197
198
199
200
201
202
203
static void
run (char    *name,
     int      nparams,
     GParam  *param,
     int     *nreturn_vals,
     GParam **return_vals)
{
  static GParam values[2];
  GRunModeType run_mode;
  GStatusType status = STATUS_SUCCESS;
204
205
206
#ifdef GIMP_HAVE_PARASITES
  Parasite *parasite;
#endif /* GIMP_HAVE_PARASITES */
Sven Neumann's avatar
Sven Neumann committed
207
  gint32 image;
Sven Neumann's avatar
Sven Neumann committed
208
209
  gint32 drawable;
  gint32 orig_image;
Sven Neumann's avatar
Sven Neumann committed
210
  GimpExportReturnType export = EXPORT_CANCEL;
Elliot Lee's avatar
Elliot Lee committed
211
212
213
214
215
216
217
218
219
220

  run_mode = param[0].data.d_int32;

  *nreturn_vals = 1;
  *return_vals = values;
  values[0].type = PARAM_STATUS;
  values[0].data.d_status = STATUS_CALLING_ERROR;

  if (strcmp (name, "file_tiff_load") == 0)
    {
Sven Neumann's avatar
Sven Neumann committed
221
      image = load_image (param[1].data.d_string);
Elliot Lee's avatar
Elliot Lee committed
222

Sven Neumann's avatar
Sven Neumann committed
223
      if (image != -1)
Elliot Lee's avatar
Elliot Lee committed
224
225
226
227
	{
	  *nreturn_vals = 2;
	  values[0].data.d_status = STATUS_SUCCESS;
	  values[1].type = PARAM_IMAGE;
Sven Neumann's avatar
Sven Neumann committed
228
	  values[1].data.d_image = image;
Elliot Lee's avatar
Elliot Lee committed
229
230
231
232
233
234
235
236
	}
      else
	{
	  values[0].data.d_status = STATUS_EXECUTION_ERROR;
	}
    }
  else if (strcmp (name, "file_tiff_save") == 0)
    {
Sven Neumann's avatar
Sven Neumann committed
237
      image = orig_image = param[1].data.d_int32;
238
      drawable = param[2].data.d_int32;
239
240
241
242

/* Do this right this time, if POSSIBLE query for parasites, otherwise
   or if there isn't one, choose the DEFAULT_COMMENT */

Sven Neumann's avatar
Sven Neumann committed
243
244
245
246
247
248
249
      /*  eventually export the image */ 
      switch (run_mode)
	{
	case RUN_INTERACTIVE:
	case RUN_WITH_LAST_VALS:
	  init_gtk ();
	  export = gimp_export_image (&image, &drawable, "TIFF", 
Sven Neumann's avatar
Sven Neumann committed
250
251
252
253
254
255
256
257
				      (CAN_HANDLE_RGB | CAN_HANDLE_GRAY | CAN_HANDLE_INDEXED | 
				       CAN_HANDLE_ALPHA));
	  if (export == EXPORT_CANCEL)
	    {
	      *nreturn_vals = 1;
	      values[0].data.d_status = STATUS_EXECUTION_ERROR;
	      return;
	    }
Sven Neumann's avatar
Sven Neumann committed
258
259
260
261
262
	  break;
	default:
	  break;
	}

263
#ifdef GIMP_HAVE_PARASITES
264

Marc Lehmann's avatar
Marc Lehmann committed
265
      parasite = gimp_image_parasite_find (orig_image, "gimp-comment");
266
      if (parasite)
Sven Neumann's avatar
Sven Neumann committed
267
        image_comment = g_strdup (parasite->data);
268
269
270
      parasite_free(parasite);
#endif /* GIMP_HAVE_PARASITES */

Sven Neumann's avatar
Sven Neumann committed
271
      if (!image_comment) image_comment = g_strdup (DEFAULT_COMMENT);	  
272

Elliot Lee's avatar
Elliot Lee committed
273
274
275
      switch (run_mode)
	{
	case RUN_INTERACTIVE:
276
	{
Elliot Lee's avatar
Elliot Lee committed
277
278
	  /*  Possibly retrieve data  */
	  gimp_get_data ("file_tiff_save", &tsvals);
279
#ifdef GIMP_HAVE_PARASITES
Marc Lehmann's avatar
Marc Lehmann committed
280
	  parasite = gimp_image_parasite_find (orig_image, "tiff-save-options");
281
	  if (parasite)
Sven Neumann's avatar
Sven Neumann committed
282
283
284
	    {
	      tsvals.compression = ((TiffSaveVals *)parasite->data)->compression;
	    }
285
	  parasite_free(parasite);
286
#endif /* GIMP_HAVE_PARASITES */
Elliot Lee's avatar
Elliot Lee committed
287
288
289
290

	  /*  First acquire information with a dialog  */
	  if (! save_dialog ())
	    return;
Sven Neumann's avatar
Sven Neumann committed
291
292
	} 
	break;
Elliot Lee's avatar
Elliot Lee committed
293
294
295

	case RUN_NONINTERACTIVE:
	  /*  Make sure all the arguments are there!  */
Nick Lamb /GIMP's avatar
Nick Lamb /GIMP committed
296
	  if (nparams != 6)
Elliot Lee's avatar
Elliot Lee committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
	    status = STATUS_CALLING_ERROR;
	  if (status == STATUS_SUCCESS)
	    {
	      switch (param[5].data.d_int32)
		{
		case 0: tsvals.compression = COMPRESSION_NONE;     break;
		case 1: tsvals.compression = COMPRESSION_LZW;      break;
		case 2: tsvals.compression = COMPRESSION_PACKBITS; break;
		default: status = STATUS_CALLING_ERROR; break;
		}
	    }

	case RUN_WITH_LAST_VALS:
	  /*  Possibly retrieve data  */
311
	{
Elliot Lee's avatar
Elliot Lee committed
312
	  gimp_get_data ("file_tiff_save", &tsvals);
313
#ifdef GIMP_HAVE_PARASITES
Marc Lehmann's avatar
Marc Lehmann committed
314
	  parasite = gimp_image_parasite_find (orig_image, "tiff-save-options");
315
	  if (parasite)
Sven Neumann's avatar
Sven Neumann committed
316
317
318
319
	    {
	      tsvals.compression = ((TiffSaveVals *)parasite->data)->compression;
	    }
	  parasite_free (parasite);
320
#endif /* GIMP_HAVE_PARASITES */
321
	}
Elliot Lee's avatar
Elliot Lee committed
322
323
324
325
326
327
328
	  break;

	default:
	  break;
	}

      *nreturn_vals = 1;
Sven Neumann's avatar
Sven Neumann committed
329
      if (save_image (param[3].data.d_string, image, drawable, orig_image))
Elliot Lee's avatar
Elliot Lee committed
330
331
332
333
334
335
336
337
	{
	  /*  Store mvals data  */
	  gimp_set_data ("file_tiff_save", &tsvals, sizeof (TiffSaveVals));

	  values[0].data.d_status = STATUS_SUCCESS;
	}
      else
	values[0].data.d_status = STATUS_EXECUTION_ERROR;
Sven Neumann's avatar
Sven Neumann committed
338

Sven Neumann's avatar
Sven Neumann committed
339
      if (export == EXPORT_EXPORT)
Sven Neumann's avatar
Sven Neumann committed
340
	gimp_image_delete (image);
Elliot Lee's avatar
Elliot Lee committed
341
342
343
    }
}

Sven Neumann's avatar
Sven Neumann committed
344
345
346
static gint32 
load_image (char *filename) 
{
Elliot Lee's avatar
Elliot Lee committed
347
  TIFF *tif;
348
  unsigned short bps, spp, photomet;
349
  int cols, rows, alpha;
350
351
  int image, image_type = RGB;
  int layer, layer_type = RGB_IMAGE;
Manish Singh's avatar
Manish Singh committed
352
  unsigned short extra, *extra_types;
353
  channel_data *channel= NULL;
Sven Neumann's avatar
Sven Neumann committed
354

355
  unsigned short *redmap, *greenmap, *bluemap;
Sven Neumann's avatar
Sven Neumann committed
356
  guchar colors[3]= {0, 0, 0};
357
  guchar cmap[768];
Sven Neumann's avatar
Sven Neumann committed
358

359
360
  int i, j, worst_case = 0;
  char *name;
Elliot Lee's avatar
Elliot Lee committed
361

362
  TiffSaveVals save_vals;
363
#ifdef GIMP_HAVE_PARASITES
364
  Parasite *parasite;
365
#endif /* GIMP_HAVE_PARASITES */
366
  guint16 tmp;
Elliot Lee's avatar
Elliot Lee committed
367
  tif = TIFFOpen (filename, "r");
Sven Neumann's avatar
Sven Neumann committed
368
  if (!tif) {
Sven Neumann's avatar
Sven Neumann committed
369
    g_message ("TIFF Can't open %s\n", filename);
Sven Neumann's avatar
Sven Neumann committed
370
371
    gimp_quit ();
  }
Elliot Lee's avatar
Elliot Lee committed
372

Sven Neumann's avatar
Sven Neumann committed
373
  name = g_malloc (strlen (filename) + 12);
Elliot Lee's avatar
Elliot Lee committed
374
375
  sprintf (name, "Loading %s:", filename);
  gimp_progress_init (name);
Sven Neumann's avatar
Sven Neumann committed
376
  g_free (name);
Elliot Lee's avatar
Elliot Lee committed
377

378
  TIFFGetFieldDefaulted (tif, TIFFTAG_BITSPERSAMPLE, &bps);
Sven Neumann's avatar
Sven Neumann committed
379

380
381
  if (bps > 8 && bps != 16) {
    worst_case = 1; /* Wrong sample width => RGBA */
Sven Neumann's avatar
Sven Neumann committed
382
383
  }

384
385
  TIFFGetFieldDefaulted (tif, TIFFTAG_SAMPLESPERPIXEL, &spp);

Sven Neumann's avatar
Sven Neumann committed
386
387
388
389
  if (!TIFFGetField (tif, TIFFTAG_EXTRASAMPLES, &extra, &extra_types))
    extra = 0;

  if (!TIFFGetField (tif, TIFFTAG_IMAGEWIDTH, &cols)) {
Sven Neumann's avatar
Sven Neumann committed
390
    g_message ("TIFF Can't get image width\n");
Sven Neumann's avatar
Sven Neumann committed
391
392
393
394
    gimp_quit ();
  }

  if (!TIFFGetField (tif, TIFFTAG_IMAGELENGTH, &rows)) {
Sven Neumann's avatar
Sven Neumann committed
395
    g_message ("TIFF Can't get image length\n");
Sven Neumann's avatar
Sven Neumann committed
396
397
398
399
    gimp_quit ();
  }

  if (!TIFFGetField (tif, TIFFTAG_PHOTOMETRIC, &photomet)) {
400
    g_message("TIFF Can't get photometric\nAssuming min-is-black\n");
401
402
403
404
405
    /* old AppleScan software misses out the photometric tag (and
     * incidentally assumes min-is-white, but xv assumes min-is-black,
     * so we follow xv's lead.  It's not much hardship to invert the
     * image later). */
    photomet = PHOTOMETRIC_MINISBLACK;
Sven Neumann's avatar
Sven Neumann committed
406
  }
Elliot Lee's avatar
Elliot Lee committed
407
408

  /* test if the extrasample represents an associated alpha channel... */
Sven Neumann's avatar
Sven Neumann committed
409
  if (extra > 0 && (extra_types[0] == EXTRASAMPLE_ASSOCALPHA)) {
Elliot Lee's avatar
Elliot Lee committed
410
    alpha = 1;
411
    --extra;
Sven Neumann's avatar
Sven Neumann committed
412
  } else {
Elliot Lee's avatar
Elliot Lee committed
413
    alpha = 0;
Sven Neumann's avatar
Sven Neumann committed
414
  }
Elliot Lee's avatar
Elliot Lee committed
415

416
  if (photomet == PHOTOMETRIC_RGB && spp > 3 + extra) {
Manish Singh's avatar
Manish Singh committed
417
    alpha= 1;
418
419
    extra= spp - 4; 
  } else if (photomet != PHOTOMETRIC_RGB && spp > 1 + extra) {
Manish Singh's avatar
Manish Singh committed
420
    alpha= 1;
421
    extra= spp - 2;
Sven Neumann's avatar
Sven Neumann committed
422
  }
Elliot Lee's avatar
Elliot Lee committed
423

Sven Neumann's avatar
Sven Neumann committed
424
425
426
  switch (photomet) {
    case PHOTOMETRIC_MINISBLACK:
    case PHOTOMETRIC_MINISWHITE:
Elliot Lee's avatar
Elliot Lee committed
427
428
      image_type = GRAY;
      layer_type = (alpha) ? GRAYA_IMAGE : GRAY_IMAGE;
Sven Neumann's avatar
Sven Neumann committed
429
      break;
Elliot Lee's avatar
Elliot Lee committed
430

Sven Neumann's avatar
Sven Neumann committed
431
432
433
434
    case PHOTOMETRIC_RGB:
      image_type = RGB;
      layer_type = (alpha) ? RGBA_IMAGE : RGB_IMAGE;
      break;
Elliot Lee's avatar
Elliot Lee committed
435

Sven Neumann's avatar
Sven Neumann committed
436
437
438
439
    case PHOTOMETRIC_PALETTE:
      image_type = INDEXED;
      layer_type = (alpha) ? INDEXEDA_IMAGE : INDEXED_IMAGE;
      break;
Elliot Lee's avatar
Elliot Lee committed
440

Sven Neumann's avatar
Sven Neumann committed
441
    default:
442
443
444
445
446
447
      worst_case = 1;
  }

  if (worst_case) {
    image_type = RGB;
    layer_type = RGBA_IMAGE;
Sven Neumann's avatar
Sven Neumann committed
448
  }
Elliot Lee's avatar
Elliot Lee committed
449

Sven Neumann's avatar
Sven Neumann committed
450
  if ((image = gimp_image_new (cols, rows, image_type)) == -1) {
Manish Singh's avatar
Manish Singh committed
451
    g_message("TIFF Can't create a new image\n");
Sven Neumann's avatar
Sven Neumann committed
452
453
454
    gimp_quit ();
  }
  gimp_image_set_filename (image, filename);
Elliot Lee's avatar
Elliot Lee committed
455

456
457
458
459
460
  /* attach a parasite containing the compression/fillorder */
  if (!TIFFGetField (tif, TIFFTAG_COMPRESSION, &tmp))
    save_vals.compression = COMPRESSION_NONE;
  else
    save_vals.compression = tmp;
461
#ifdef GIMP_HAVE_PARASITES
462
463
  parasite = parasite_new("tiff-save-options", 0,
			  sizeof(save_vals), &save_vals);
Marc Lehmann's avatar
Marc Lehmann committed
464
  gimp_image_parasite_attach(image, parasite);
465
  parasite_free(parasite);
466
#endif /* GIMP_HAVE_PARASITES */
467

468

469
  /* Attach a parasite containing the image description.  Pretend to
470
   * be a gimp comment so other plugins will use this description as
471
   * an image comment where appropriate. */
472
#ifdef GIMP_HAVE_PARASITES
473
474
475
476
477
478
479
480
481
482
483
  {
    char *img_desc;

    if (TIFFGetField (tif, TIFFTAG_IMAGEDESCRIPTION, &img_desc))
    {
      int len;

      len = strlen(img_desc) + 1;
      len = MIN(len, 241);
      img_desc[len-1] = '\000';

Sven Neumann's avatar
Sven Neumann committed
484
485
      parasite = parasite_new ("gimp-comment", PARASITE_PERSISTENT,
			       len, img_desc);
Marc Lehmann's avatar
Marc Lehmann committed
486
      gimp_image_parasite_attach (image, parasite);
Sven Neumann's avatar
Sven Neumann committed
487
      parasite_free (parasite);
488
489
    }
  }
490
#endif /* GIMP_HAVE_PARASITES */
491

492
  /* any resolution info in the file? */
493
#ifdef GIMP_HAVE_RESOLUTION_INFO
494
  {
495
496
497
    float xres = 72.0, yres = 72.0;
    unsigned short read_unit;
    GUnit unit = UNIT_PIXEL; /* invalid unit */
498
499
500
501

    if (TIFFGetField (tif, TIFFTAG_XRESOLUTION, &xres)) {
      if (TIFFGetField (tif, TIFFTAG_YRESOLUTION, &yres)) {

Sven Neumann's avatar
Sven Neumann committed
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
	if (TIFFGetFieldDefaulted (tif, TIFFTAG_RESOLUTIONUNIT, &read_unit)) 
	  {
	    switch (read_unit) 
	      {
	      case RESUNIT_NONE:
		/* ImageMagick writes files with this silly resunit */
		g_message ("TIFF warning: resolution units meaningless, "
			   "forcing 72 dpi\n");
		break;
		
	      case RESUNIT_INCH:
		unit = UNIT_INCH;
		break;
		
	      case RESUNIT_CENTIMETER:
		xres *= 2.54;
		yres *= 2.54;
		unit = UNIT_MM; /* as this is our default metric unit */
		break;
		
	      default:
		g_message ("TIFF file error: unknown resolution unit type %d, "
			   "assuming dpi\n", read_unit);
	      }
	  } 
	else 
	  { /* no res unit tag */
	    /* old AppleScan software produces these */
	    g_message ("TIFF warning: resolution specified without\n"
		       "any units tag, assuming dpi\n");
532
	  }
Sven Neumann's avatar
Sven Neumann committed
533
534
535
536
537
      } 
      else 
	{ /* xres but no yres */
	  g_message("TIFF warning: no y resolution info, assuming same as x\n");
	  yres = xres;
538
539
540
	}

      /* sanity check, since division by zero later could be embarrassing */
Sven Neumann's avatar
Sven Neumann committed
541
542
543
      if (xres < 1e-5 || yres < 1e-5) 
	{
	g_message ("TIFF: image resolution is zero: forcing 72 dpi\n");
544
545
	xres = 72.0;
	yres = 72.0;
546
547
548
      }

      /* now set the new image's resolution info */
549
      gimp_image_set_resolution (image, xres, yres);
550
      if (unit != UNIT_PIXEL)
551
	gimp_image_set_unit (image, unit);
552
553
554
555
556
557
558
559
560
561
562
    }

    /* no x res tag => we assume we have no resolution info, so we
     * don't care.  Older versions of this plugin used to write files
     * with no resolution tags at all. */

    /* TODO: haven't caught the case where yres tag is present, but
       not xres.  This is left as an exercise for the reader - they
       should feel free to shoot the author of the broken program
       that produced the damaged TIFF file in the first place. */
  }
563
#endif /* GIMP_HAVE_RESOLUTION_INFO */
564
565


Sven Neumann's avatar
Sven Neumann committed
566
  /* Install colormap for INDEXED images only */
Sven Neumann's avatar
Sven Neumann committed
567
568
569
570
571
572
573
  if (image_type == INDEXED) 
    {
      if (!TIFFGetField (tif, TIFFTAG_COLORMAP, &redmap, &greenmap, &bluemap)) 
	{
	  g_message ("TIFF Can't get colormaps\n");
	  gimp_quit ();
	}
Elliot Lee's avatar
Elliot Lee committed
574

Sven Neumann's avatar
Sven Neumann committed
575
576
577
578
579
580
581
      for (i = 0, j = 0; i < (1 << bps); i++) 
	{
	  cmap[j++] = redmap[i] >> 8;
	  cmap[j++] = greenmap[i] >> 8;
	  cmap[j++] = bluemap[i] >> 8;
	}
      gimp_image_set_cmap (image, cmap, (1 << bps));
Elliot Lee's avatar
Elliot Lee committed
582
583
    }

584
585
  /* Allocate channel_data for all channels, even the background layer */
  channel = g_new (channel_data, extra + 1);
Sven Neumann's avatar
Sven Neumann committed
586
  layer = gimp_layer_new (image, "Background", cols, rows, layer_type,
Elliot Lee's avatar
Elliot Lee committed
587
			     100, NORMAL_MODE);
588
  channel[0].ID= layer;
Sven Neumann's avatar
Sven Neumann committed
589
  gimp_image_add_layer (image, layer, 0);
590
  channel[0].drawable= gimp_drawable_get(layer);
591

592
  if (extra > 0 && !worst_case) {
593
    /* Add alpha channels as appropriate */
594
    for (i= 1; i <= extra; ++i) {
595
596
597
598
599
600
601
      channel[i].ID= gimp_channel_new(image, "TIFF Channel", cols, rows,
                                                            100.0, colors);
      gimp_image_add_channel(image, channel[i].ID, 0);
      channel[i].drawable= gimp_drawable_get (channel[i].ID);
    }
  }

602
603
604
605
606
607
608
  if (worst_case) {
    g_message("TIFF Fell back to RGBA, image may be inverted\n");
    load_rgba (tif, channel);
  } else if (TIFFIsTiled(tif)) {
    load_tiles (tif, channel, bps, photomet, alpha, extra);
  } else { /* Load scanlines in tile_height chunks */
    load_lines (tif, channel, bps, photomet, alpha, extra);
609
610
611
612
613
614
615
616
617
618
619
  }

  for (i= 0; i < extra; ++i) {
    gimp_drawable_flush (channel[i].drawable);
    gimp_drawable_detach (channel[i].drawable);
  }

  return image;
}

static void
620
load_rgba (TIFF *tif, channel_data *channel)
621
{
622
  uint32 imageWidth, imageLength;
Tomas Ogren's avatar
Tomas Ogren committed
623
  gulong *buffer;
624
625
626
627
628

  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &imageWidth);
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &imageLength);
  gimp_pixel_rgn_init (&(channel[0].pixel_rgn), channel[0].drawable,
                          0, 0, imageWidth, imageLength, TRUE, FALSE);
Tomas Ogren's avatar
Tomas Ogren committed
629
  buffer = g_new(gulong, imageWidth * imageLength);
630
631
632
633
634
635
  channel[0].pixels = (guchar*) buffer;
  if (buffer == NULL) {
    g_message("TIFF Unable to allocate temporary buffer\n");
  }
  if (!TIFFReadRGBAImage(tif, imageWidth, imageLength, buffer, 0))
    g_message("TIFF Unsupported layout, no RGBA loader\n");
636

637
638
639
640
  gimp_pixel_rgn_set_rect(&(channel[0].pixel_rgn), channel[0].pixels,
                              0, 0, imageWidth, imageLength);
  g_message("TIFF Fell back to RGBA, image may be inverted\n");
}
Elliot Lee's avatar
Elliot Lee committed
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
static void
load_tiles (TIFF *tif, channel_data *channel,
	   unsigned short bps, unsigned short photomet,
	   int alpha, int extra)
{
  uint16 planar= PLANARCONFIG_CONTIG;
  uint32 imageWidth, imageLength;
  uint32 tileWidth, tileLength;
  uint32 x, y, rows, cols;
  guchar *buffer;
  double progress= 0.0, one_row;
  int i;

  TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planar);
  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &imageWidth);
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &imageLength);
  TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tileWidth);
  TIFFGetField(tif, TIFFTAG_TILELENGTH, &tileLength);
  one_row = (double) tileLength / (double) imageLength;
  buffer = g_malloc(TIFFTileSize(tif));

  for (i= 0; i <= extra; ++i) {
    channel[i].pixels= g_new(guchar, tileWidth * tileLength *
                                      channel[i].drawable->bpp);
  }
667

668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
  for (y = 0; y < imageLength; y += tileLength) {
    for (x = 0; x < imageWidth; x += tileWidth) {
      gimp_progress_update (progress + one_row *
                            ( (double) x / (double) imageWidth));
      TIFFReadTile(tif, buffer, x, y, 0, 0);
      cols= MIN(imageWidth - x, tileWidth);
      rows= MIN(imageLength - y, tileLength);
      if (bps == 16) {
        read_16bit(buffer, channel, photomet, y, x, rows, cols, alpha, extra);
      } else if (bps == 8) {
        read_8bit(buffer, channel, photomet, y, x, rows, cols, alpha, extra);
      } else {
        read_default(buffer, channel, bps, photomet,
                          y, x, rows, cols, alpha, extra);
      }
683
    }
684
685
686
687
688
689
690
691
692
693
    progress+= one_row;
  }
  for (i= 0; i <= extra; ++i) {
    g_free(channel[i].pixels);
  }
  g_free(buffer);
}

static void
load_lines (TIFF *tif, channel_data *channel,
Sven Neumann's avatar
Sven Neumann committed
694
695
	    unsigned short bps, unsigned short photomet,
	    int alpha, int extra)
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
{
  uint16 planar= PLANARCONFIG_CONTIG;
  uint32 imageLength, lineSize, cols, rows;
  guchar *buffer;
  int i, y, tile_height = gimp_tile_height ();

  TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planar);
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &imageLength);
  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &cols);
  lineSize= TIFFScanlineSize(tif);

  for (i= 0; i <= extra; ++i) {
    channel[i].pixels= g_new(guchar, tile_height * cols
                                          * channel[i].drawable->bpp);
  }
711

712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
  buffer = g_malloc(lineSize * tile_height);
  if (planar == PLANARCONFIG_CONTIG) {
    for (y = 0; y < imageLength; y+= tile_height ) {
      gimp_progress_update ( (double) y / (double) imageLength);
      rows = MIN(tile_height, imageLength - y);
      for (i = 0; i < rows; ++i)
	TIFFReadScanline(tif, buffer + i * lineSize, y + i, 0);
      if (bps == 16) {
	read_16bit(buffer, channel, photomet, y, 0, rows, cols, alpha, extra);
      } else if (bps == 8) {
	read_8bit(buffer, channel, photomet, y, 0, rows, cols, alpha, extra);
      } else {
	read_default(buffer, channel, bps, photomet,
                             y, 0, rows, cols, alpha, extra);
      }
727
    }
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
  } else { /* PLANARCONFIG_SEPARATE  -- Just say "No" */
    uint16 s, samples;
    TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samples);
    for (s = 0; s < samples; ++s) {
      for (y = 0; y < imageLength; y+= tile_height ) {
	gimp_progress_update ( (double) y / (double) imageLength);
	rows = MIN(tile_height, imageLength - y);
	for (i = 0; i < rows; ++i)
	  TIFFReadScanline(tif, buffer + i * lineSize, y + i, s);
	read_separate (buffer, channel, bps, photomet,
		         y, 0, rows, cols, alpha, extra, s);
      }
    }
  }
  for (i= 0; i <= extra; ++i) {
    g_free(channel[i].pixels);
  }
  g_free(buffer);
}
747

748
static void
Sven Neumann's avatar
Sven Neumann committed
749
750
751
read_16bit (guchar *source, channel_data *channel, unsigned short photomet,
	    int startrow, int startcol, int rows, int cols,
	    int alpha, int extra)
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
{
  guchar *dest;
  int gray_val, red_val, green_val, blue_val, alpha_val;
  int col, row, i;

  for (i= 0; i <= extra; ++i) {
    gimp_pixel_rgn_init (&(channel[i].pixel_rgn), channel[i].drawable,
                          startcol, startrow, cols, rows, TRUE, FALSE);
  }

  for (row = 0; row < rows; ++row) {
    dest= channel[0].pixels + row * cols * channel[0].drawable->bpp;

    for (i= 1; i <= extra; ++i) {
      channel[i].pixel= channel[i].pixels + row * cols;
    }
Elliot Lee's avatar
Elliot Lee committed
768

769
770
771
772
    for (col = 0; col < cols; col++) {
      switch (photomet) {
        case PHOTOMETRIC_MINISBLACK:
          if (alpha) {
773
774
            gray_val= *source; source+= 2;
            alpha_val= *source; source+= 2;
775
            if (alpha_val)
776
              *dest++ = gray_val * 255 / alpha_val;
777
            else
778
779
              *dest++ = 0;
            *dest++ = alpha_val;
780
          } else {
781
            *dest++ = *source; source+= 2;
782
783
          }
          break;
Elliot Lee's avatar
Elliot Lee committed
784

785
786
        case PHOTOMETRIC_MINISWHITE:
          if (alpha) {
787
788
            gray_val= *source; source+= 2;
            alpha_val= *source; source+= 2;
789
            if (alpha_val)
790
              *dest++ = ((255 - gray_val) * 255) / alpha_val;
791
            else
792
793
              *dest++ = 0;
            *dest++ = alpha_val;
794
          } else {
795
            *dest++ = ~(*source); source+= 2;
796
797
798
799
          }
          break;

        case PHOTOMETRIC_PALETTE:
800
801
          *dest++= *source; source+= 2;
          if (alpha) *dest++= *source; source+= 2;
802
803
804
805
          break;
  
        case PHOTOMETRIC_RGB:
          if (alpha) {
806
807
808
809
            red_val= *source; source+= 2;
            green_val= *source; source+= 2;
            blue_val= *source; source+= 2;
            alpha_val= *source; source+= 2;
810
            if (alpha_val) {
811
812
813
              *dest++ = (red_val * 255) / alpha_val;
              *dest++ = (green_val * 255) / alpha_val;
              *dest++ = (blue_val * 255) / alpha_val;
814
            } else {
815
816
817
              *dest++ = 0;
              *dest++ = 0;
              *dest++ = 0;
818
	    }
819
	    *dest++ = alpha_val;
820
	  } else {
821
822
823
	    *dest++ = *source; source+= 2;
	    *dest++ = *source; source+= 2;
	    *dest++ = *source; source+= 2;
824
825
826
827
828
829
830
	  }
          break;

        default:
          /* This case was handled earlier */
          g_assert_not_reached();
      }
831
832
      for (i= 1; i <= extra; ++i) {
        *channel[i].pixel++ = *source; source+= 2;
833
834
      }
    }
835
836
837
838
839
840
841
842
  }
  for (i= 0; i <= extra; ++i) {
    gimp_pixel_rgn_set_rect(&(channel[i].pixel_rgn), channel[i].pixels,
                              startcol, startrow, cols, rows);
  }
}

static void
Sven Neumann's avatar
Sven Neumann committed
843
844
845
read_8bit (guchar *source, channel_data *channel, unsigned short photomet,
	   int startrow, int startcol, int rows, int cols,
	   int alpha, int extra)
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
{
  guchar *dest;
  int gray_val, red_val, green_val, blue_val, alpha_val;
  int col, row, i;

  for (i= 0; i <= extra; ++i) {
    gimp_pixel_rgn_init (&(channel[i].pixel_rgn), channel[i].drawable,
                          startcol, startrow, cols, rows, TRUE, FALSE);
  }

  for (row = 0; row < rows; ++row) {
    dest= channel[0].pixels + row * cols * channel[0].drawable->bpp;

    for (i= 1; i <= extra; ++i) {
      channel[i].pixel= channel[i].pixels + row * cols;
    }

    for (col = 0; col < cols; col++) {
      switch (photomet) {
        case PHOTOMETRIC_MINISBLACK:
          if (alpha) {
            gray_val= *source++;
            alpha_val= *source++;
            if (alpha_val)
              *dest++ = gray_val * 255 / alpha_val;
            else
              *dest++ = 0;
            *dest++ = alpha_val;
          } else {
            *dest++ = *source++;
          }
          break;

        case PHOTOMETRIC_MINISWHITE:
          if (alpha) {
            gray_val= *source++;
            alpha_val= *source++;
            if (alpha_val)
              *dest++ = ((255 - gray_val) * 255) / alpha_val;
            else
              *dest++ = 0;
            *dest++ = alpha_val;
          } else {
            *dest++ = ~(*source++);
          }
          break;

        case PHOTOMETRIC_PALETTE:
          *dest++= *source++;
          if (alpha) *dest++= *source++;
          break;
  
        case PHOTOMETRIC_RGB:
          if (alpha) {
            red_val= *source++;
            green_val= *source++;
            blue_val= *source++;
            alpha_val= *source++;
            if (alpha_val) {
              *dest++ = (red_val * 255) / alpha_val;
              *dest++ = (green_val * 255) / alpha_val;
              *dest++ = (blue_val * 255) / alpha_val;
            } else {
              *dest++ = 0;
              *dest++ = 0;
              *dest++ = 0;
	    }
	    *dest++ = alpha_val;
	  } else {
	    *dest++ = *source++;
	    *dest++ = *source++;
	    *dest++ = *source++;
	  }
          break;

        default:
          /* This case was handled earlier */
          g_assert_not_reached();
      }
      for (i= 1; i <= extra; ++i) {
        *channel[i].pixel++ = *source++;
927
928
      }
    }
Sven Neumann's avatar
Sven Neumann committed
929
  }
930
931
932
933
  for (i= 0; i <= extra; ++i) {
    gimp_pixel_rgn_set_rect(&(channel[i].pixel_rgn), channel[i].pixels,
                              startcol, startrow, cols, rows);
  }
934
}
Elliot Lee's avatar
Elliot Lee committed
935

Sven Neumann's avatar
Sven Neumann committed
936
937
938
/* Step through all <= 8-bit samples in an image */

#define NEXTSAMPLE(var)                       \
Elliot Lee's avatar
Elliot Lee committed
939
  {                                           \
Sven Neumann's avatar
Sven Neumann committed
940
      if (bitsleft == 0)                      \
Elliot Lee's avatar
Elliot Lee committed
941
      {                                       \
942
	  source++;                           \
Elliot Lee's avatar
Elliot Lee committed
943
944
945
	  bitsleft = 8;                       \
      }                                       \
      bitsleft -= bps;                        \
946
      var = ( *source >> bitsleft ) & maxval; \
Elliot Lee's avatar
Elliot Lee committed
947
948
  }

949
static void
Sven Neumann's avatar
Sven Neumann committed
950
951
952
953
read_default (guchar *source, channel_data *channel,
	      unsigned short bps, unsigned short photomet,
	      int startrow, int startcol, int rows, int cols,
	      int alpha, int extra)
954
{
955
  guchar *dest;
956
  int gray_val, red_val, green_val, blue_val, alpha_val;
957
958
  int col, row, i;
  int bitsleft = 8, maxval = (1 << bps) - 1;
959

960
961
962
963
  for (i= 0; i <= extra; ++i) {
    gimp_pixel_rgn_init (&(channel[i].pixel_rgn), channel[i].drawable,
		startcol, startrow, cols, rows, TRUE, FALSE);
  }
Sven Neumann's avatar
Sven Neumann committed
964

965
966
  for (row = 0; row < rows; ++row) {
    dest= channel[0].pixels + row * cols * channel[0].drawable->bpp;
Sven Neumann's avatar
Sven Neumann committed
967

968
969
    for (i= 1; i <= extra; ++i) {
      channel[i].pixel= channel[i].pixels + row * cols;
970
    }
Sven Neumann's avatar
Sven Neumann committed
971

972
    for (col = 0; col < cols; col++) {
Sven Neumann's avatar
Sven Neumann committed
973
974
      switch (photomet) {
        case PHOTOMETRIC_MINISBLACK:
975
976
977
978
          NEXTSAMPLE(gray_val);
          if (alpha) {
            NEXTSAMPLE(alpha_val);
            if (alpha_val)
979
              *dest++ = (gray_val * 65025) / (alpha_val * maxval);
980
            else
981
982
              *dest++ = 0;
            *dest++ = alpha_val;
983
          } else {
984
            *dest++ = (gray_val * 255) / maxval;
985
986
          }
          break;
Elliot Lee's avatar
Elliot Lee committed
987

Sven Neumann's avatar
Sven Neumann committed
988
        case PHOTOMETRIC_MINISWHITE:
989
990
991
992
          NEXTSAMPLE(gray_val);
          if (alpha) {
            NEXTSAMPLE(alpha_val);
            if (alpha_val)
993
              *dest++ = ((maxval - gray_val) * 65025) / (alpha_val * maxval);
994
            else
995
996
              *dest++ = 0;
            *dest++ = alpha_val;
997
          } else {
998
            *dest++ = ((maxval - gray_val) * 255) / maxval;
Sven Neumann's avatar
Sven Neumann committed
999
1000
1001
1002
          }
          break;

        case PHOTOMETRIC_PALETTE:
1003
          NEXTSAMPLE(*dest++);
1004
          if (alpha) {
1005
            NEXTSAMPLE(*dest++);
Sven Neumann's avatar
Sven Neumann committed
1006
1007
1008
1009
          }
          break;
  
        case PHOTOMETRIC_RGB:
1010
1011
1012
1013
1014
1015
          NEXTSAMPLE(red_val)
          NEXTSAMPLE(green_val)
          NEXTSAMPLE(blue_val)
          if (alpha) {
            NEXTSAMPLE(alpha_val)
            if (alpha_val) {
1016
1017
1018
              *dest++ = (red_val * 255) / alpha_val;
              *dest++ = (green_val * 255) / alpha_val;
              *dest++ = (blue_val * 255) / alpha_val;
1019
            } else {
1020
1021
1022
              *dest++ = 0;
              *dest++ = 0;
              *dest++ = 0;
Elliot Lee's avatar
Elliot Lee committed
1023
	    }
1024
	    *dest++ = alpha_val;
1025
	  } else {
1026
1027
1028
	    *dest++ = red_val;
	    *dest++ = green_val;
	    *dest++ = blue_val;
1029
	  }
Sven Neumann's avatar
Sven Neumann committed
1030
1031
1032
1033
1034
1035
          break;

        default:
          /* This case was handled earlier */
          g_assert_not_reached();
      }
1036
      for (i= 1; i <= extra; ++i) {
1037
1038
1039
        NEXTSAMPLE(alpha_val);
        *channel[i].pixel++ = alpha_val;
      }
Sven Neumann's avatar
Sven Neumann committed
1040
    }
1041
1042
1043
1044
1045
    bitsleft= 0;
  }
  for (i= 0; i <= extra; ++i) {
    gimp_pixel_rgn_set_rect(&(channel[i].pixel_rgn), channel[i].pixels,
                              startcol, startrow, cols, rows);
Sven Neumann's avatar
Sven Neumann committed
1046
  }
1047
}
Elliot Lee's avatar
Elliot Lee committed
1048

1049
static void
1050
1051
1052
1053
read_separate (guchar *source, channel_data *channel,
               unsigned short bps, unsigned short photomet,
               int startrow, int startcol, int rows, int cols,
               int alpha, int extra, int sample)
1054
{
1055
1056
1057
  guchar *dest;
  int col, row, c;
  int bitsleft = 8, maxval = (1 << bps) - 1;
Elliot Lee's avatar
Elliot Lee committed
1058

1059
1060
  if (bps > 8) {
    g_message("TIFF Unsupported layout\n");
1061
1062
1063
    gimp_quit();
  }

1064
1065
1066
1067
1068
  if (sample < channel[0].drawable->bpp) {
    c = 0;
  } else {
    c = (sample - channel[0].drawable->bpp) + 4;
    photomet = PHOTOMETRIC_MINISBLACK;
1069
1070
  }

1071
1072
  gimp_pixel_rgn_init (&(channel[c].pixel_rgn), channel[c].drawable,
                         startcol, startrow, cols, rows, TRUE, FALSE);
1073

1074
1075
1076
1077
1078
1079
1080
  gimp_pixel_rgn_get_rect(&(channel[c].pixel_rgn), channel[c].pixels,
                            startcol, startrow, cols, rows);
  for (row = 0; row < rows; ++row) {
    dest = channel[c].pixels + row * cols * channel[c].drawable->bpp;
    if (c == 0) {
      for (col = 0; col < cols; ++col) {
        NEXTSAMPLE(dest[col * channel[0].drawable->bpp + sample]);
1081
      }
1082
1083
1084
    } else {
      for (col = 0; col < cols; ++col)
        NEXTSAMPLE(dest[col]);
1085
1086
    }
  }
1087
1088
  gimp_pixel_rgn_set_rect(&(channel[c].pixel_rgn), channel[c].pixels,
                            startcol, startrow, cols, rows);
Elliot Lee's avatar
Elliot Lee committed
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
}

/*
** pnmtotiff.c - converts a portable anymap to a Tagged Image File
**
** Derived by Jef Poskanzer from ras2tif.c, which is:
**
** Copyright (c) 1990 by Sun Microsystems, Inc.
**
** Author: Patrick J. Naughton
** naughton@wind.sun.com
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation.
**
** This file is provided AS IS with no warranties of any kind.  The author
** shall have no liability with respect to the infringement of copyrights,
** trade secrets or any patents by this file or any part thereof.  In no
** event will the author be liable for any lost revenue or profits or
** other special, indirect and consequential damages.
*/

Sven Neumann's avatar
Sven Neumann committed
1114
1115
1116
1117
1118
static gint save_image (char   *filename, 
			gint32  image, 
			gint32  layer,
			gint32  orig_image)  /* the export function might have created a duplicate */  
{
Elliot Lee's avatar
Elliot Lee committed
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
  TIFF *tif;
  unsigned short red[256];
  unsigned short grn[256];
  unsigned short blu[256];
  int cols, col, rows, row, i;
  long g3options;
  long rowsperstrip;
  unsigned short compression;
  unsigned short extra_samples[1];
  int alpha;
  short predictor;
  short photometric;
  short samplesperpixel;
  short bitspersample;
  int bytesperrow;
  guchar *t, *src, *data;
  guchar *cmap;
  int colors;
  int success;
  GDrawable *drawable;
  GDrawableType drawable_type;
  GPixelRgn pixel_rgn;
  int tile_height;
  int y, yend;
  char *name;

  compression = tsvals.compression;

  g3options = 0;
  predictor = 0;
  rowsperstrip = 0;

  tif = TIFFOpen (filename, "w");
Sven Neumann's avatar
Sven Neumann committed
1152
1153
1154
1155
1156
  if (!tif) 
    {
      g_print ("Can't write image to\n%s", filename);
      return 0;
    }
Elliot Lee's avatar
Elliot Lee committed
1157
1158
1159
1160
1161
1162

  name = malloc (strlen (filename) + 11);
  sprintf (name, "Saving %s:", filename);
  gimp_progress_init (name);
  free (name);

Sven Neumann's avatar
Sven Neumann committed
1163
1164
  drawable = gimp_drawable_get (layer);
  drawable_type = gimp_drawable_type (layer);
Elliot Lee's avatar
Elliot Lee committed
1165
1166
1167
1168
1169
1170
1171
1172
  gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, drawable->width, drawable->height, FALSE, FALSE);

  cols = drawable->width;
  rows = drawable->height;

  switch (drawable_type)
    {
    case RGB_IMAGE:
1173
      predictor = 2;
Elliot Lee's avatar
Elliot Lee committed
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
      samplesperpixel = 3;
      bitspersample = 8;
      photometric = PHOTOMETRIC_RGB;
      bytesperrow = cols * 3;
      alpha = 0;
      break;
    case GRAY_IMAGE:
      samplesperpixel = 1;
      bitspersample = 8;
      photometric = PHOTOMETRIC_MINISBLACK;
      bytesperrow = cols;
      alpha = 0;
      break;
    case RGBA_IMAGE:
1188
      predictor = 2;
Elliot Lee's avatar
Elliot Lee committed
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
      samplesperpixel = 4;
      bitspersample = 8;
      photometric = PHOTOMETRIC_RGB;
      bytesperrow = cols * 4;
      alpha = 1;
      break;
    case GRAYA_IMAGE:
      samplesperpixel = 2;
      bitspersample = 8;
      photometric = PHOTOMETRIC_MINISBLACK;
      bytesperrow = cols * 2;
      alpha = 1;
      break;
    case INDEXED_IMAGE:
      samplesperpixel = 1;
      bitspersample = 8;
      photometric = PHOTOMETRIC_PALETTE;
      bytesperrow = cols;
      alpha = 0;

Sven Neumann's avatar
Sven Neumann committed
1209
      cmap = gimp_image_get_cmap (image, &colors);
Elliot Lee's avatar
Elliot Lee committed
1210
1211
1212

      for (i = 0; i < colors; i++)
	{
1213
1214
1215
	  red[i] = *cmap++ * 65535 / 255;
	  grn[i] = *cmap++ * 65535 / 255;
	  blu[i] = *cmap++ * 65535 / 255;
Elliot Lee's avatar
Elliot Lee committed
1216
1217
1218
1219
	}
      break;
    case INDEXEDA_IMAGE:
      return 0;
1220
     default:
1221
      return 0;
Elliot Lee's avatar
Elliot Lee committed
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
    }

  if (rowsperstrip == 0)
    rowsperstrip = (8 * 1024) / bytesperrow;
  if (rowsperstrip == 0)
    rowsperstrip = 1;

  /* Set TIFF parameters. */
  TIFFSetField (tif, TIFFTAG_IMAGEWIDTH, cols);
  TIFFSetField (tif, TIFFTAG_IMAGELENGTH, rows);
  TIFFSetField (tif, TIFFTAG_BITSPERSAMPLE, bitspersample);
  TIFFSetField (tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
  TIFFSetField (tif, TIFFTAG_COMPRESSION, compression);
  if ((compression == COMPRESSION_LZW) && (predictor != 0))
    TIFFSetField (tif, TIFFTAG_PREDICTOR, predictor);
  if (alpha)
    {
      extra_samples [0] = EXTRASAMPLE_ASSOCALPHA;
      TIFFSetField (tif, TIFFTAG_EXTRASAMPLES, 1, extra_samples);
    }
  TIFFSetField (tif, TIFFTAG_PHOTOMETRIC, photometric);
  TIFFSetField (tif, TIFFTAG_DOCUMENTNAME, filename);
  TIFFSetField (tif, TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
  TIFFSetField (tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
  /* TIFFSetField( tif, TIFFTAG_STRIPBYTECOUNTS, rows / rowsperstrip ); */
  TIFFSetField (tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);

1249
#ifdef GIMP_HAVE_RESOLUTION_INFO
1250
1251
  /* resolution fields */
  {
1252
1253
1254
1255
1256
1257
    double xresolution;
    double yresolution;
    unsigned short save_unit = RESUNIT_INCH;
    GUnit unit;
    float factor;

Sven Neumann's avatar
Sven Neumann committed
1258
1259
    gimp_image_get_resolution (orig_image, &xresolution, &yresolution);
    unit = gimp_image_get_unit (orig_image);
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
    factor = gimp_unit_get_factor (unit);

    /*  if we have a metric unit, save the resolution as centimeters
     */
    if ((ABS(factor - 0.0254) < 1e-5) ||  /* m */
	(ABS(factor - 0.254) < 1e-5) ||   /* why not ;) */
	(ABS(factor - 2.54) < 1e-5) ||    /* cm */
	(ABS(factor - 25.4) < 1e-5))      /* mm */
      {
	save_unit = RESUNIT_CENTIMETER;
	xresolution /= 2.54;