tiff.c 45.1 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
40
41
#ifdef GIMP_HAVE_RESOLUTION_INFO
#include "libgimp/gimpunit.h"
#endif
42

Elliot Lee's avatar
Elliot Lee committed
43
44
45
46
47
48
49
50
51
52
53
typedef struct
{
  gint  compression;
  gint  fillorder;
} TiffSaveVals;

typedef struct
{
  gint  run;
} TiffSaveInterface;

54
55
56
57
58
59
60
61
typedef struct {
  gint32 ID;
  GDrawable *drawable;
  GPixelRgn pixel_rgn;
  guchar *pixels;
  guchar *pixel;
} channel_data;

Elliot Lee's avatar
Elliot Lee committed
62
63
64
65
66
67
68
69
70
/* 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);
71
72
73
74
75
76

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,
77
                         unsigned short bps, unsigned short photomet,
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
                         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,
93
                            unsigned short bps, unsigned short photomet,
94
95
96
                            int startcol, int startrow, int rows, int cols,
                            int alpha, int extra);

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

Sven Neumann's avatar
Sven Neumann committed
102
static void   init_gtk ();
Elliot Lee's avatar
Elliot Lee committed
103
104
105
106
107
108
109
110
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);
111
112
static void   comment_entry_callback  (GtkWidget *widget,
				       gpointer   data);
Elliot Lee's avatar
Elliot Lee committed
113

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

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  */
};

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

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" },
161
    { PARAM_INT32, "compression", "Compression type: { NONE (0), LZW (1), PACKBITS (2)" },
Elliot Lee's avatar
Elliot Lee committed
162
163
164
165
166
167
  };
  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
168
                          "Spencer Kimball, Peter Mattis & Nick Lamb",
Manish Singh's avatar
Manish Singh committed
169
                          "Nick Lamb <njl195@zepler.org.uk>",
170
                          "1995-1996,1998-1999",
Elliot Lee's avatar
Elliot Lee committed
171
172
173
174
175
176
177
178
179
180
181
182
183
                          "<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
184
			  "RGB*, GRAY*, INDEXED",
Elliot Lee's avatar
Elliot Lee committed
185
186
187
188
189
190
191
192
193
                          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", "");
}

194
195
196



Elliot Lee's avatar
Elliot Lee committed
197
198
199
200
201
202
203
204
205
206
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;
207
208
209
#ifdef GIMP_HAVE_PARASITES
  Parasite *parasite;
#endif /* GIMP_HAVE_PARASITES */
Sven Neumann's avatar
Sven Neumann committed
210
  gint32 image;
Sven Neumann's avatar
Sven Neumann committed
211
212
  gint32 drawable;
  gint32 orig_image;
Sven Neumann's avatar
Sven Neumann committed
213
  GimpExportReturnType export = EXPORT_CANCEL;
Elliot Lee's avatar
Elliot Lee committed
214
215
216
217
218
219
220
221
222
223

  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
224
      image = load_image (param[1].data.d_string);
Elliot Lee's avatar
Elliot Lee committed
225

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

/* 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
246
247
248
249
250
251
252
      /*  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
253
254
255
256
257
258
259
260
				      (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
261
262
263
264
265
	  break;
	default:
	  break;
	}

266
#ifdef GIMP_HAVE_PARASITES
267

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

Sven Neumann's avatar
Sven Neumann committed
274
      if (!image_comment) image_comment = g_strdup (DEFAULT_COMMENT);	  
275

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

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

	case RUN_NONINTERACTIVE:
	  /*  Make sure all the arguments are there!  */
Nick Lamb /GIMP's avatar
Nick Lamb /GIMP committed
299
	  if (nparams != 6)
Elliot Lee's avatar
Elliot Lee committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
	    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  */
314
	{
Elliot Lee's avatar
Elliot Lee committed
315
	  gimp_get_data ("file_tiff_save", &tsvals);
316
#ifdef GIMP_HAVE_PARASITES
Marc Lehmann's avatar
Marc Lehmann committed
317
	  parasite = gimp_image_parasite_find (orig_image, "tiff-save-options");
318
	  if (parasite)
Sven Neumann's avatar
Sven Neumann committed
319
320
321
322
	    {
	      tsvals.compression = ((TiffSaveVals *)parasite->data)->compression;
	    }
	  parasite_free (parasite);
323
#endif /* GIMP_HAVE_PARASITES */
324
	}
Elliot Lee's avatar
Elliot Lee committed
325
326
327
328
329
330
331
	  break;

	default:
	  break;
	}

      *nreturn_vals = 1;
Sven Neumann's avatar
Sven Neumann committed
332
      if (save_image (param[3].data.d_string, image, drawable, orig_image))
Elliot Lee's avatar
Elliot Lee committed
333
334
335
336
337
338
339
340
	{
	  /*  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
341

Sven Neumann's avatar
Sven Neumann committed
342
      if (export == EXPORT_EXPORT)
Sven Neumann's avatar
Sven Neumann committed
343
	gimp_image_delete (image);
Elliot Lee's avatar
Elliot Lee committed
344
345
346
    }
}

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

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

362
363
  int i, j, worst_case = 0;
  char *name;
Elliot Lee's avatar
Elliot Lee committed
364

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

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

381
  TIFFGetFieldDefaulted (tif, TIFFTAG_BITSPERSAMPLE, &bps);
Sven Neumann's avatar
Sven Neumann committed
382

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

387
388
  TIFFGetFieldDefaulted (tif, TIFFTAG_SAMPLESPERPIXEL, &spp);

Sven Neumann's avatar
Sven Neumann committed
389
390
391
392
  if (!TIFFGetField (tif, TIFFTAG_EXTRASAMPLES, &extra, &extra_types))
    extra = 0;

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

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

  if (!TIFFGetField (tif, TIFFTAG_PHOTOMETRIC, &photomet)) {
403
    g_message("TIFF Can't get photometric\nAssuming min-is-black\n");
404
405
406
407
408
    /* 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
409
  }
Elliot Lee's avatar
Elliot Lee committed
410
411

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

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

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

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

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

Sven Neumann's avatar
Sven Neumann committed
444
    default:
445
446
447
448
449
450
      worst_case = 1;
  }

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

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

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

471

472
  /* Attach a parasite containing the image description.  Pretend to
473
   * be a gimp comment so other plugins will use this description as
474
   * an image comment where appropriate. */
475
#ifdef GIMP_HAVE_PARASITES
476
477
478
479
480
481
482
483
484
485
486
  {
    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
487
488
      parasite = parasite_new ("gimp-comment", PARASITE_PERSISTENT,
			       len, img_desc);
Marc Lehmann's avatar
Marc Lehmann committed
489
      gimp_image_parasite_attach (image, parasite);
Sven Neumann's avatar
Sven Neumann committed
490
      parasite_free (parasite);
491
492
    }
  }
493
#endif /* GIMP_HAVE_PARASITES */
494

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

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

Sven Neumann's avatar
Sven Neumann committed
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
	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");
535
	  }
Sven Neumann's avatar
Sven Neumann committed
536
537
538
539
540
      } 
      else 
	{ /* xres but no yres */
	  g_message("TIFF warning: no y resolution info, assuming same as x\n");
	  yres = xres;
541
542
543
	}

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

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

    /* 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. */
  }
566
#endif /* GIMP_HAVE_RESOLUTION_INFO */
567
568


Sven Neumann's avatar
Sven Neumann committed
569
  /* Install colormap for INDEXED images only */
Sven Neumann's avatar
Sven Neumann committed
570
571
572
573
574
575
576
  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
577

Sven Neumann's avatar
Sven Neumann committed
578
579
580
581
582
583
584
      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
585
586
    }

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

595
  if (extra > 0 && !worst_case) {
596
    /* Add alpha channels as appropriate */
597
    for (i= 1; i <= extra; ++i) {
598
599
600
601
602
603
604
      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);
    }
  }

605
606
607
608
609
610
611
  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);
612
613
614
615
616
617
618
619
620
621
622
  }

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

  return image;
}

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

  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
632
  buffer = g_new(gulong, imageWidth * imageLength);
633
634
635
636
637
638
  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");
639

640
641
642
643
  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
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
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);
  }
670

671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
  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);
      }
686
    }
687
688
689
690
691
692
693
694
695
696
    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
697
698
	    unsigned short bps, unsigned short photomet,
	    int alpha, int extra)
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
{
  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);
  }
714

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
  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);
      }
730
    }
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
  } 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);
}
750

751
static void
Sven Neumann's avatar
Sven Neumann committed
752
753
754
read_16bit (guchar *source, channel_data *channel, unsigned short photomet,
	    int startrow, int startcol, int rows, int cols,
	    int alpha, int extra)
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
{
  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
771

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

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

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

        default:
          /* This case was handled earlier */
          g_assert_not_reached();
      }
834
835
      for (i= 1; i <= extra; ++i) {
        *channel[i].pixel++ = *source; source+= 2;
836
837
      }
    }
838
839
840
841
842
843
844
845
  }
  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
846
847
848
read_8bit (guchar *source, channel_data *channel, unsigned short photomet,
	   int startrow, int startcol, int rows, int cols,
	   int alpha, int extra)
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
{
  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++;
930
931
      }
    }
Sven Neumann's avatar
Sven Neumann committed
932
  }
933
934
935
936
  for (i= 0; i <= extra; ++i) {
    gimp_pixel_rgn_set_rect(&(channel[i].pixel_rgn), channel[i].pixels,
                              startcol, startrow, cols, rows);
  }
937
}
Elliot Lee's avatar
Elliot Lee committed
938

Sven Neumann's avatar
Sven Neumann committed
939
940
941
/* Step through all <= 8-bit samples in an image */

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

952
static void
Sven Neumann's avatar
Sven Neumann committed
953
954
955
956
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)
957
{
958
  guchar *dest;
959
  int gray_val, red_val, green_val, blue_val, alpha_val;
960
961
  int col, row, i;
  int bitsleft = 8, maxval = (1 << bps) - 1;
962

963
964
965
966
  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
967

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

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

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

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

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

        default:
          /* This case was handled earlier */
          g_assert_not_reached();
      }
1039
      for (i= 1; i <= extra; ++i) {
1040
1041
1042
        NEXTSAMPLE(alpha_val);
        *channel[i].pixel++ = alpha_val;
      }
Sven Neumann's avatar
Sven Neumann committed
1043
    }
1044
1045
1046
1047
1048
    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
1049
  }
1050
}
Elliot Lee's avatar
Elliot Lee committed
1051

1052
static void
1053
1054
1055
1056
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)
1057
{
1058
1059
1060
  guchar *dest;
  int col, row, c;
  int bitsleft = 8, maxval = (1 << bps) - 1;
Elliot Lee's avatar
Elliot Lee committed
1061

1062
1063
  if (bps > 8) {
    g_message("TIFF Unsupported layout\n");
1064
1065
1066
    gimp_quit();
  }

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

1074
1075
  gimp_pixel_rgn_init (&(channel[c].pixel_rgn), channel[c].drawable,
                         startcol, startrow, cols, rows, TRUE, FALSE);
1076

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

/*
** 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
1117
1118
1119
1120
1121
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
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
  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
1155
1156
1157
1158
1159
  if (!tif) 
    {
      g_print ("Can't write image to\n%s", filename);
      return 0;
    }
Elliot Lee's avatar
Elliot Lee committed
1160
1161
1162
1163
1164
1165

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

Sven Neumann's avatar
Sven Neumann committed
1166
1167
  drawable = gimp_drawable_get (layer);
  drawable_type = gimp_drawable_type (layer);
Elliot Lee's avatar
Elliot Lee committed
1168
1169
1170
1171
1172
1173
1174
1175
  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:
1176
      predictor = 2;
Elliot Lee's avatar
Elliot Lee committed
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
      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:
1191
      predictor = 2;
Elliot Lee's avatar
Elliot Lee committed
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
      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
1212
      cmap = gimp_image_get_cmap (image, &colors);
Elliot Lee's avatar
Elliot Lee committed
1213
1214
1215

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

  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);

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

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