Пример #1
0
int
write_strips(TIFF *tif, const tdata_t array, const tsize_t size)
{
    tstrip_t	strip, nstrips;
    tsize_t		stripsize, offset;

    stripsize = TIFFStripSize(tif);
    if (!stripsize) {
        fprintf (stderr, "Wrong size of strip.\n");
        return -1;
    }

    nstrips = TIFFNumberOfStrips(tif);
    for (offset = 0, strip = 0;
            offset < size && strip < nstrips;
            offset+=stripsize, strip++) {
        /*
         * Properly write last strip.
         */
        tsize_t	bufsize = size - offset;
        if (bufsize > stripsize)
            bufsize = stripsize;

        if (TIFFWriteEncodedStrip(tif, strip, (char *)array + offset,
                                  bufsize) != bufsize) {
            fprintf (stderr, "Can't write strip %lu.\n",
                     (unsigned long)strip);
            return -1;
        }
    }

    return 0;
}
static int
cpStrips(TIFF* in, TIFF* out)
{
    tsize_t bufsize  = TIFFStripSize(in);
    unsigned char *buf = (unsigned char *)_TIFFmalloc(bufsize);

    if (buf) {
	tstrip_t s, ns = TIFFNumberOfStrips(in);
	tsize_t *bytecounts;

	TIFFGetField(in, TIFFTAG_STRIPBYTECOUNTS, &bytecounts);
	for (s = 0; s < ns; s++) {
	    if (bytecounts[s] > bufsize) {
		buf = (unsigned char *)_TIFFrealloc(buf, bytecounts[s]);
		if (!buf)
		    goto bad;
		bufsize = bytecounts[s];
	    }
	    if (TIFFReadRawStrip(in, s, buf, bytecounts[s]) < 0 ||
		TIFFWriteRawStrip(out, s, buf, bytecounts[s]) < 0) {
		_TIFFfree(buf);
		return 0;
	    }
	}
	_TIFFfree(buf);
	return 1;
    }

bad:
	TIFFError(TIFFFileName(in),
		  "Can't allocate space for strip buffer.");
	return 0;
}
Пример #3
0
static int
cpStrips(TIFF* in, TIFF* out)
{
	tmsize_t bufsize  = TIFFStripSize(in);
	unsigned char *buf = (unsigned char *)_TIFFmalloc(bufsize);

	if (buf) {
		tstrip_t s, ns = TIFFNumberOfStrips(in);
		uint64 *bytecounts;

		TIFFGetField(in, TIFFTAG_STRIPBYTECOUNTS, &bytecounts);
		for (s = 0; s < ns; s++) {
			if (bytecounts[s] > (uint64)bufsize) {
				buf = (unsigned char *)_TIFFrealloc(buf, (tmsize_t)bytecounts[s]);
				if (!buf)
					return (0);
				bufsize = (tmsize_t)bytecounts[s];
			}
			if (TIFFReadRawStrip(in, s, buf, (tmsize_t)bytecounts[s]) < 0 ||
			    TIFFWriteRawStrip(out, s, buf, (tmsize_t)bytecounts[s]) < 0) {
				_TIFFfree(buf);
				return (0);
			}
		}
		_TIFFfree(buf);
		return (1);
	}
	return (0);
}
Пример #4
0
tdata_t tif_ReadContigStripData(TIFF* tif)
{
  tdata_t raster = tif_Malloc(tif);

  tsize_t  result;
  tsize_t  offset;
  tsize_t  stripSize = TIFFStripSize(tif);
  tstrip_t stripMax = TIFFNumberOfStrips(tif);
  tstrip_t istrip; 

  if (tif == NULL)
    return NULL;

  offset = 0;
  if (raster != NULL) { 
    for (istrip = 0; istrip < stripMax; istrip++){
      result = TIFFReadEncodedStrip (tif, istrip, ((char*)raster)+offset, stripSize);
        if (result == -1) {
          printf("Read error on input strip number %d\n", istrip);
        }
        offset += result;
    }
  }
  return raster;
}
Пример #5
0
int
TIFFSetupStrips(TIFF* tif)
{
	TIFFDirectory* td = &tif->tif_dir;

	if (isTiled(tif))
		td->td_stripsperimage =
		    isUnspecified(tif, FIELD_TILEDIMENSIONS) ?
			td->td_samplesperpixel : TIFFNumberOfTiles(tif);
	else
		td->td_stripsperimage =
		    isUnspecified(tif, FIELD_ROWSPERSTRIP) ?
			td->td_samplesperpixel : TIFFNumberOfStrips(tif);
	td->td_nstrips = td->td_stripsperimage;
	if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
		td->td_stripsperimage /= td->td_samplesperpixel;
	td->td_stripoffset = (uint64 *)
	    _TIFFmalloc(td->td_nstrips * sizeof (uint64));
	td->td_stripbytecount = (uint64 *)
	    _TIFFmalloc(td->td_nstrips * sizeof (uint64));
	if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL)
		return (0);
	/*
	 * Place data at the end-of-file
	 * (by setting offsets to zero).
	 */
	_TIFFmemset(td->td_stripoffset, 0, td->td_nstrips*sizeof (uint64));
	_TIFFmemset(td->td_stripbytecount, 0, td->td_nstrips*sizeof (uint64));
	TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
	TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
	return (1);
}
Пример #6
0
static int
cpStrips(TIFF* in, TIFF* out)
{
	tsize_t bufsize  = TIFFStripSize(in);
	unsigned char *buf = (unsigned char *)_TIFFmalloc(bufsize);

	if (buf) {
		tstrip_t s, ns = TIFFNumberOfStrips(in);
		uint32 *bytecounts;

		if (!TIFFGetField(in, TIFFTAG_STRIPBYTECOUNTS, &bytecounts)) {
			fprintf(stderr, "tiffsplit: strip byte counts are missing\n");
			return (0);
		}
		for (s = 0; s < ns; s++) {
			if (bytecounts[s] > (uint32)bufsize) {
				buf = (unsigned char *)_TIFFrealloc(buf, bytecounts[s]);
				if (!buf)
					return (0);
				bufsize = bytecounts[s];
			}
			if (TIFFReadRawStrip(in, s, buf, bytecounts[s]) < 0 ||
			    TIFFWriteRawStrip(out, s, buf, bytecounts[s]) < 0) {
				_TIFFfree(buf);
				return (0);
			}
		}
		_TIFFfree(buf);
		return (1);
	}
	return (0);
}
Пример #7
0
bool CaViewerCore::openTif(ImageInfo info, int nSequence)
{
    static const QString sProgressFormat = QObject::tr("Loading... %p%");

    TIFF* tif = TIFFOpen(info.fullName(nSequence).toStdString().c_str(), "r");
    quint16 bps, spp;
    quint32 rps;
    TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bps);
    TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &spp);
    TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rps);

    const quint32 stripSize = TIFFNumberOfStrips(tif);
    const quint32 stripLength = TIFFStripSize(tif);

    int nPrevImgCount = 0;
    for(int count = 0; count < nSequence; ++count)
        nPrevImgCount += info.imageSize(count);

    if(bps == 16 && spp == 1)   //  for 16-bit mono channel tif
    {
        for(int imgCount = 0; imgCount < info.imageSize(nSequence); ++imgCount)
        {
            const int globalCount = nPrevImgCount + imgCount;
            const int height = globalCount % info.heightSize();
            const int time = globalCount / info.heightSize();
            cv::Mat_<quint16> img = m_lImage->at(height).at(time);

#pragma omp parallel for schedule(static)
            for(quint32 stripCount = 0; stripCount < stripSize; ++stripCount)
            {
                quint16* const stripBuf = reinterpret_cast<quint16*>(new quint8[stripLength]);
#pragma omp critical
                TIFFReadEncodedStrip(tif, stripCount, stripBuf, stripLength);
                for(quint32 rowInStrip = 0; rowInStrip < rps; ++rowInStrip)
                {
                    const quint32 imgStrip = rowInStrip + rps * stripCount;
                    quint16* const matData = reinterpret_cast<quint16*>(img.data + img.step * imgStrip);
                    for(int col = 0; col < info.colSize(); ++col)
                    {
                        const quint16 oriValue = stripBuf[col + rowInStrip * info.colSize()];
                        matData[col] = oriValue;
                    }

                    if(imgStrip == info.rowSize() - 1)
                        break;
                }
            }

            TIFFReadDirectory(tif);

            emit changedProgressValue(100.0 * globalCount / m_lImage->size(), sProgressFormat);
        }
        return true;
    }
    else
        return false;

    TIFFClose(tif);
}
Пример #8
0
static
int StripBasedXform(cmsHTRANSFORM hXForm, TIFF* in, TIFF* out, int nPlanes)
{
    tsize_t BufSizeIn  = TIFFStripSize(in);
    tsize_t BufSizeOut = TIFFStripSize(out);
    unsigned char *BufferIn, *BufferOut;
    ttile_t i, StripCount = TIFFNumberOfStrips(in) / nPlanes;
    uint32 sw;
    uint32 sl;
    uint32 iml;
    int j;
    int PixelCount;

    TIFFGetFieldDefaulted(in, TIFFTAG_IMAGEWIDTH,  &sw);
    TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &sl);
    TIFFGetFieldDefaulted(in, TIFFTAG_IMAGELENGTH, &iml);

   

    BufferIn = (unsigned char *) _TIFFmalloc(BufSizeIn * nPlanes);
    if (!BufferIn) OutOfMem(BufSizeIn * nPlanes);

    BufferOut = (unsigned char *) _TIFFmalloc(BufSizeOut * nPlanes);
    if (!BufferOut) OutOfMem(BufSizeOut * nPlanes);


    for (i = 0; i < StripCount; i++) {

        for (j=0; j < nPlanes; j++) {

            if (TIFFReadEncodedStrip(in, i + (j * StripCount), 
                                        BufferIn + (j * BufSizeIn), BufSizeIn) < 0)   goto cleanup;
        }

        PixelCount = (int) sw * (iml < sl ? iml : sl);
        iml -= sl;

        cmsDoTransform(hXForm, BufferIn, BufferOut, PixelCount);

        for (j=0; j < nPlanes; j++) {
            if (TIFFWriteEncodedStrip(out, i + (j * StripCount), 
                                     BufferOut + j * BufSizeOut, BufSizeOut) < 0) goto cleanup;
        }

    }

    _TIFFfree(BufferIn);
    _TIFFfree(BufferOut);
    return 1;


cleanup:

    _TIFFfree(BufferIn);
   _TIFFfree(BufferOut);
   return 0;
}
Пример #9
0
int
rut_surface_to_tiff (RutSurface *s, const char *filename)
{
  TIFF *tif = NULL;
  int rows_per_strip, num_strips, strip, row, i;
  int result = 1;
  char *buffer = NULL;

  assert (s);
  assert (filename);

  /* Open TIFF file */
  tif = TIFFOpen (filename, "wb");
  if (!tif) goto savefail;

  /* Set TIFF tags */
  TIFFSetField (tif, TIFFTAG_IMAGEWIDTH, s->cols);
  TIFFSetField (tif, TIFFTAG_IMAGELENGTH, s->rows);
  TIFFSetField (tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
  TIFFSetField (tif, TIFFTAG_BITSPERSAMPLE, 32);
  TIFFSetField (tif, TIFFTAG_SAMPLESPERPIXEL, 1);
  TIFFSetField (tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);

  rows_per_strip = TIFFDefaultStripSize (tif, 0);
  TIFFSetField (tif, TIFFTAG_ROWSPERSTRIP, rows_per_strip);
  num_strips = TIFFNumberOfStrips (tif);

  /* Copy data into TIFF strips */
  buffer = malloc (TIFFStripSize (tif));

  for (row = 0, strip = 0; strip < num_strips; strip++) {
    size_t size = 0;
    for (i = 0; (i < rows_per_strip) && (row < s->rows); i++, row++) {
      float *src = RUT_SURFACE_PTR (s, row, 0);
      char *dest = buffer + i*s->cols*4;
      memcpy (dest, src, s->cols * 4);
      size += s->cols*4;
    }
    result = (TIFFWriteEncodedStrip (tif, strip, buffer, size) != -1);
    if (!result) {
      fprintf (stderr, "Could not write TIFF strip %i/%i to %s\n",
               strip+1, num_strips, filename);
    }
  }

  /* Clean up */
  free (buffer);
  TIFFClose (tif);
  return 1;

 savefail:
  if (tif) TIFFClose (tif);
  if (buffer) free (buffer);
  fprintf (stderr, "Could not save TIFF to %s\n", filename);
  return 0;
}
Пример #10
0
static int JBIGSetupEncode(TIFF* tif)
{
        if (TIFFNumberOfStrips(tif) != 1)
        {
                TIFFError("JBIG", "Multistrip images not supported in encoder");
                return 0;
        }

        return 1;
}
Пример #11
0
static int JBIGSetupDecode(TIFF* tif)
{
	if (TIFFNumberOfStrips(tif) != 1)
	{
		TIFFErrorExt(tif->tif_clientdata, "JBIG", "Multistrip images not supported in decoder");
		return 0;
	}

	return 1;
}
Пример #12
0
int tiffSize_(TIFF *image, int *W, int *H, int *linestep, BufType *Type)
{
  uint16 bps, spp, sfm;
  uint32 width;
  tsize_t stripSize;
  unsigned long imageOffset;
  int stripMax;
  
  //unsigned long bufferSize, count;
  
  // Check that it is of a type that we support
  if((TIFFGetField(image, TIFFTAG_BITSPERSAMPLE, &bps) == 0) ){
    return(42);
  }
  
  MyTRACE( "bits per sample(%d)\n", bps);

  //float type
   if((TIFFGetField(image, TIFFTAG_SAMPLEFORMAT, &sfm) == 0) ){
    
    return(42);
  }

   MyTRACE( "TIFFTAG_SAMPLEFORMAT(%d)\n", sfm);

   if (bps == 32 && sfm == SAMPLEFORMAT_IEEEFP)
	   *Type = TYPE_32F;
   else if (bps == 16 && (sfm == SAMPLEFORMAT_INT))
	   *Type = TYPE_16S;
   else if (bps == 16 && (sfm == SAMPLEFORMAT_UINT))
	   *Type = TYPE_16U;
   else
	   return 43;

  if((TIFFGetField(image, TIFFTAG_SAMPLESPERPIXEL, &spp) == 0) || (spp != 1)){
    MyTRACE( "Either undefined or unsupported number of samples per pixel\n");
    return(42);
  }
  // Read in the possibly multiple strips
  stripSize = TIFFStripSize (image);
  *linestep = stripSize;
  stripMax = TIFFNumberOfStrips (image);
  imageOffset = 0;
  long height = stripMax;
  *H = height;
  // Do whatever it is we do with the buffer -- we dump it in hex
  if(TIFFGetField(image, TIFFTAG_IMAGEWIDTH, &width) == 0){
    MyTRACE( "Image does not define its width\n");
    return(42);
  }
  *W = width;

  assert(typeSize(*Type)*width <= stripSize);
  return 0;
}
Пример #13
0
void
printTIF(TIFF* tif, int pageNumber)
{
    uint32 w, h;
    uint16 unit;
    float xres, yres;
    tstrip_t s, ns;

    TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
    TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
    if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres)) {
	TIFFWarning(TIFFFileName(tif),
	    "No x-resolution, assuming %g dpi", defxres);
	xres = defxres;
    }
    if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres)) {
	TIFFWarning(TIFFFileName(tif),
	    "No y-resolution, assuming %g lpi", defyres);
	yres = defyres;					/* XXX */
    }
    if (TIFFGetField(tif, TIFFTAG_RESOLUTIONUNIT, &unit) &&
      unit == RESUNIT_CENTIMETER) {
	xres *= 25.4;
	yres *= 25.4;
    }

    printf("%%%%Page: \"%d\" %d\n", pageNumber, pageNumber);
    printf("/$pageTop save def gsave\n");
    if (scaleToPage) {
	float yscale = pageHeight / (h/yres);
	float xscale = pageWidth / (w/xres);
	printf("%d %d translate\n",
               (int) (((basePageWidth - pageWidth) * points) * half),
               (int)((yscale*(h/yres)*points) +
               (basePageHeight - pageHeight) * points * half)  );
	printf("%g %g scale\n", (72.*xscale)/xres, -(72.*yscale)/yres);
    } else {
	printf("%d %d translate\n",
               (int) ((basePageWidth - pageWidth) * points * half),
               (int)((72.*h/yres) +
               (basePageHeight - pageHeight) * points * half) );
	printf("%g %g scale\n", 72./xres, -72./yres);
    }
    printf("0 setgray\n");
    TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, printruns);
    ns = TIFFNumberOfStrips(tif);
    row = 0;
    for (s = 0; s < ns; s++)
	(void) TIFFReadEncodedStrip(tif, s, (tdata_t) NULL, (tsize_t) -1);
    printf("p\n");
    printf("grestore $pageTop restore\n");
    totalPages++;
}
Пример #14
0
int tifinit(Mytiff * mytiff,const char * const filename){
   int myerror;
   char * Stripbytes=NULL;
   u_int32_t stripbytes,estsize,estbytes;

   
   myerror=0;
   mytiff->ndata=mytiff->wd * mytiff->ht;
   mytiff->nbytes = mytiff->ndata * mytiff->bytes;
   mytiff->tiffp= TIFFOpen(filename,"wl");
   if (mytiff->tiffp == 0 ){
      fprintf(stderr,"ERROR: %s: %i:  failed tiff open of %s!\n",__func__,__LINE__,filename);
      fprintf(stderr,"ERROR: %s: tried to open with TIFFOpen(%s,\"wl\");  \n",__func__,filename);
      return(101);
   } 
   TIFFSetField(mytiff->tiffp,TIFFTAG_IMAGEWIDTH,mytiff->wd);
   TIFFSetField(mytiff->tiffp,TIFFTAG_IMAGELENGTH,mytiff->ht);
   TIFFSetField(mytiff->tiffp,TIFFTAG_BITSPERSAMPLE,mytiff->bytes * 8);
   TIFFSetField(mytiff->tiffp,TIFFTAG_PLANARCONFIG,1);
   TIFFSetField(mytiff->tiffp,TIFFTAG_PHOTOMETRIC,1);

   /* only 4-byte float or 2-byte int so far */

   if (mytiff->bytes == 4){
      TIFFSetField(mytiff->tiffp,TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
   }else if (mytiff->bytes == 2){
      TIFFSetField(mytiff->tiffp,TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
   }

   /* set the number of rows per strip , default or overridden by the environment variable */

   Stripbytes=getenv("I12STRIPBYTES");
   if (Stripbytes == NULL ){
      stripbytes=(D_STRIPBYTES);
   }else{
      stripbytes=atoi(Stripbytes);
   }

   estbytes=(stripbytes / (mytiff->wd * mytiff->bytes));
   estsize=TIFFDefaultStripSize(mytiff->tiffp,estbytes);
   TIFFSetField(mytiff->tiffp,TIFFTAG_ROWSPERSTRIP,estsize);
   mytiff->stripnum=TIFFNumberOfStrips(mytiff->tiffp);
   mytiff->bytesperstrip=TIFFVStripSize(mytiff->tiffp,mytiff->stripnum);
   if (! mytiff->isalloc){
      mytiff->buf=(char *) malloc(mytiff->bytesperstrip);
      mytiff->isalloc=1;
   }

   VBPRINT("stripbytes %s requested, stripsize set to: %i rows\n",Stripbytes,estsize);
   VBPRINT("bytes per strip is: %i \n",mytiff->bytesperstrip);

   return(0);
}
Пример #15
0
int
read_strips(TIFF *tif, const tdata_t array, const tsize_t size)
{
    tstrip_t	strip, nstrips;
    tsize_t		stripsize, offset;
    tdata_t		buf = NULL;

    stripsize = TIFFStripSize(tif);
    if (!stripsize) {
        fprintf (stderr, "Wrong size of strip.\n");
        return -1;
    }

    buf = _TIFFmalloc(stripsize);
    if (!buf) {
        fprintf (stderr, "Can't allocate space for strip buffer.\n");
        return -1;
    }

    nstrips = TIFFNumberOfStrips(tif);
    for (offset = 0, strip = 0;
            offset < size && strip < nstrips;
            offset+=stripsize, strip++) {
        /*
         * Properly read last strip.
         */
        tsize_t	bufsize = size - offset;
        if (bufsize > stripsize)
            bufsize = stripsize;

        if (TIFFReadEncodedStrip(tif, strip, buf, -1) != bufsize) {
            fprintf (stderr, "Can't read strip %lu.\n",
                     (unsigned long)strip);
            return -1;
        }
        if (memcmp(buf, (char *)array + offset, bufsize) != 0) {
            fprintf (stderr, "Wrong data read for strip %lu.\n",
                     (unsigned long)strip);
            _TIFFfree(buf);
            return -1;
        }
    }

    _TIFFfree(buf);

    return 0;
}
Пример #16
0
        /**
         * Constructor.
         *
         * @param ifd the directory the tile belongs to.
         */
        Impl(std::shared_ptr<IFD>& ifd):
          ifd(ifd),
          tilewidth(),
          tileheight(),
          planarconfig(),
          samples(),
          tilecount(),
          nrows(),
          ncols(),
          ntiles(),
          buffersize()
        {
          Sentry sentry;
          ::TIFF *tiff = getTIFF();

          // Get basic image metadata.
          uint32_t imagewidth = ifd->getImageWidth();
          uint32_t imageheight = ifd->getImageHeight();
          planarconfig = ifd->getPlanarConfiguration();
          samples = ifd->getSamplesPerPixel();
          tilewidth = ifd->getTileWidth();
          tileheight = ifd->getTileHeight();
          type = ifd->getTileType();

          // Get tile-specific metadata, falling back to
          // strip-specific metadata if not present.
          if (type == TILE)
            {
              tilecount = TIFFNumberOfTiles(tiff);
              buffersize = TIFFTileSize(tiff);
            }
          else
            {
              tilecount = TIFFNumberOfStrips(tiff);
              buffersize = TIFFStripSize(tiff);
            }

          // Compute row and column counts.
          nrows = imageheight / tileheight;
          if (imageheight % tileheight)
            ++nrows;
          ncols = imagewidth / tilewidth;
          if (imagewidth % tilewidth)
            ++ncols;
          ntiles = nrows * ncols;
        }
Пример #17
0
void stkGetOffsets(TIFF *tif, DTiffParams *tiffParams ) {
  /*
  the default libtiff strip reading is not good enough since it only gives us strip offsets for 
  the first plane although all the offsets for all the planes are actually stored
  so for uncompressed images use default and for LZW the custom methods
  */
  
  DStkInfo *stkInfo = &tiffParams->stkInfo;
  stkInfo->strips_per_plane = TIFFNumberOfStrips( tif );

  if (stkInfo->strip_offsets != NULL) _TIFFfree(stkInfo->strip_offsets);
  stkInfo->strip_offsets = NULL;
  if (stkInfo->strip_bytecounts != NULL) _TIFFfree(stkInfo->strip_bytecounts);
  stkInfo->strip_bytecounts = NULL;

  if (tiffParams == NULL) return;
  if (tiffParams->dimTiff == NULL) return;
  if (tiffParams->subType != tstStk) return;

  TDimTiffIFD *ifd = &tiffParams->ifds.ifds[0];
  int N = tiffParams->stkInfo.metaData.N;
  uint32 tag = 0;

  // -----------------------------
  // read Strip Offsets
  // -----------------------------
  tag = 273;
  if (isTagPresentInFirstIFD( &tiffParams->ifds, tag ) == TRUE) {
    uint32 *buf=NULL, size=0, type=0;
    readTiffTag ( tif, ifd, tag, size, type, (DIM_UCHAR **) &buf );
    copy_clean_tag_buffer<uint32, D_TIFF_OFFS_TYPE>( &buf, size, &stkInfo->strip_offsets );

  } // strip offsets
  
  // -----------------------------
  // read strip_bytecounts also
  // -----------------------------
  tag = 279;
  if (isTagPresentInFirstIFD( &tiffParams->ifds, tag ) == TRUE) {
    uint32 *buf=NULL, size=0, type=0;
    readTiffTag ( tif, ifd, tag, size, type, (DIM_UCHAR **) &buf );
    copy_clean_tag_buffer<uint32, D_TIFF_BCNT_TYPE>( &buf, size, &stkInfo->strip_bytecounts );
  } // strip_bytecounts
}
Пример #18
0
/****************** Will hopefully remove this function. ***********************
 * Read image strips and set global variablels.
 *	- NUMBER_OF_ROWS / IMAGE_LENGTH
 *	- NUMBER_OF_COLS / IMAGE_WIDTH
 *	- IMAGE
 */
void stripIO(TIFF * tif)
{
	uint16 config;
	TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &config);
	
	int stripSize, stripMax;
	stripSize = TIFFStripSize (tif);
	stripMax  = TIFFNumberOfStrips (tif);
	
	int bytesPerStrip;
	TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &bytesPerStrip);
	
	printf("stripSize : %d  stripMax : %d bytesPerStrip : %d\n", stripSize, stripMax, bytesPerStrip);
	
	unsigned long bufferSize;
	bufferSize = stripSize * stripMax;
	
	char * buffer;
	if((buffer = (char *) _TIFFmalloc(bufferSize)) == NULL){
	    puts("Not enough memory to allocate buffer.");
	    exit(42);
	}
	
	int stripCount, result;
	unsigned long imageOffset = 0;
	for(stripCount = 0; stripCount < stripMax; stripCount++)
	{
	    if((result = TIFFReadRawStrip(tif, stripCount, buffer + imageOffset, stripSize)) == -1){
		    puts("Read error on input strip.");
	    }
	}
	
	int i;
	for(stripCount = 0; stripCount < stripMax; stripCount++){
	    for(i = 0; i < stripSize; i++){
		    //printf("%d ", atoi(&buffer[stripCount*stripSize + stripSize]));
	    }
	    //printf("\n");
	}
	
	_TIFFfree(buffer);
}
Пример #19
0
/*
 * Setup strips/tiles; buffers will be allocated in TIFFSetOffset / TIFFSetByteCount
 */
int
TIFFSetupStrips(TIFF* tif)
{
	TIFFDirectory* td = &tif->tif_dir;

	if (isTiled(tif))
		td->td_stripsperimage =
		    isUnspecified(tif, FIELD_TILEDIMENSIONS) ?
			td->td_samplesperpixel : TIFFNumberOfTiles(tif);
	else
		td->td_stripsperimage =
		    isUnspecified(tif, FIELD_ROWSPERSTRIP) ?
			td->td_samplesperpixel : TIFFNumberOfStrips(tif);
	td->td_nstrips = td->td_stripsperimage;
	if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
		td->td_stripsperimage /= td->td_samplesperpixel;
	TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS);
	TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
	return (1);
}
Пример #20
0
int ReadTiff(const char * filename,
  std::vector<unsigned char> * ptr,
  int * w,
  int * h,
  int * depth)
{
  TIFF* tiff = TIFFOpen(filename, "r");
  if (!tiff) {
    std::cerr << "Error: Couldn't open " << filename << " fopen returned 0";
    return 0;
  }
  uint16 bps, spp;

  TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, w);
  TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, h);
  TIFFGetField(tiff, TIFFTAG_BITSPERSAMPLE, &bps);
  TIFFGetField(tiff, TIFFTAG_SAMPLESPERPIXEL, &spp);
  *depth = bps * spp / 8;

  ptr->resize((*h)*(*w)*(*depth));

  if (*depth==4) {
    if (ptr != nullptr) {
      if (!TIFFReadRGBAImageOriented(tiff, *w, *h, (uint32*)&((*ptr)[0]), ORIENTATION_TOPLEFT, 0)) {
        TIFFClose(tiff);
        return 0;
      }
    }
  } else {
    for (size_t i=0; i<TIFFNumberOfStrips(tiff); ++i) {
      if (TIFFReadEncodedStrip(tiff, i, ((uint8*)&((*ptr)[0]))+i*TIFFStripSize(tiff),(tsize_t)-1) ==
        std::numeric_limits<tsize_t>::max()) {
        TIFFClose(tiff);
        return 0;
      }
    }
  }
  TIFFClose(tiff);
  return 1;
}
Пример #21
0
std::auto_ptr<image_list> STKFormat::read_multi(byte_source* src, ImageFactory* factory) {
    shift_source moved(src);
    stk_extend ext;
    tiff_warn_error twe;

    tif_holder t = read_client(&moved);
    std::auto_ptr<image_list> images(new image_list);
    const uint32 h = tiff_get<uint32>(t, TIFFTAG_IMAGELENGTH);
    const uint32 w = tiff_get<uint32>(t, TIFFTAG_IMAGEWIDTH);

    const uint16 nr_samples = tiff_get<uint16>(t, TIFFTAG_SAMPLESPERPIXEL, 1);
    const uint16 bits_per_sample = tiff_get<uint16>(t, TIFFTAG_BITSPERSAMPLE, 8);
    const int depth = nr_samples > 1 ? nr_samples : -1;

    const int strip_size = TIFFStripSize(t.tif);
    const int n_strips = TIFFNumberOfStrips(t.tif);
    int32_t n_planes;
    void* data;
    TIFFGetField(t.tif, UIC3Tag, &n_planes, &data);
    int raw_strip_size = 0;
    for (int st = 0; st != n_strips; ++st) {
        raw_strip_size += TIFFRawStripSize(t.tif, st);
    }
    for (int z = 0; z < n_planes; ++z) {
        // Monkey patch strip offsets. This is very hacky, but it seems to work!
        moved.shift(z * raw_strip_size);

        std::auto_ptr<Image> output(factory->create(bits_per_sample, h, w, depth));
        uint8_t* start = output->rowp_as<uint8_t>(0);
        for (int st = 0; st != n_strips; ++st) {
            const int offset = TIFFReadEncodedStrip(t.tif, st, start, strip_size);
            if (offset == -1) {
                throw CannotReadError("imread.imread._tiff.stk: Error reading strip");
            }
            start += offset;
        }
        images->push_back(output);
    }
    return images;
}
Пример #22
0
int tiff_decode_complex(TIFF *tif, clFFT_Complex *buffer, int offset)
{
  const int strip_size = TIFFStripSize(tif);
  const int n_strips = TIFFNumberOfStrips(tif);

  printf("\nstrip_size:%d ; n_strips:%d\n", strip_size, n_strips);

  int result = 0;

  int width, height;

  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);

  float *temp_buffer = (float *)malloc(strip_size);

  for (int strip = 0; strip < n_strips; strip++) {
	  result = TIFFReadEncodedStrip(tif, strip, temp_buffer, strip_size);

	  if (result == -1)
		  return 0;

	  int pixels_per_strip = strip_size / sizeof(float);
	  int rows = pixels_per_strip / width;

	  for(int i = 0; i < rows; ++i) {
		  for(int j = offset; j < width; ++j) {
	          buffer[strip * (pixels_per_strip - rows * offset) + i * (width-offset) + j - offset].real = temp_buffer[i * width + j];
	          buffer[strip * (pixels_per_strip - rows * offset) + i * (width-offset) + j - offset].imag = 0.0;
	      }
	  }
  }

  free(temp_buffer);

  return 1;
}
Пример #23
0
void
XdmfTIFFController::read(XdmfArray * const array)
{
  TIFF* tif = TIFFOpen(mFilePath.c_str(), "r");

  unsigned int compression = 0;

  TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression);

  unsigned int currentDirectory = 0;

  if (tif && mStart.size() >= 3) {
    // setting the start for the first directory
    TIFFSetDirectory(tif, mStart[2]);
    currentDirectory = mStart[2];
  }

  unsigned int amountWritten = 0;
  // Only used for 1d controllers
  unsigned int sizeLeft = this->getSize();
  if (!array->isInitialized()) {
    array->initialize(this->getType());
  }
  if (array->getSize() != this->getSize()) {
    array->resize(mDimensions, 0);
  }

  // For single dimension version only
  unsigned int currentRowStart = mStart[0];
  unsigned int scanlineIndex = 0;

  if (mDimensions.size() > 1)
  {
    scanlineIndex = mStart[1];
  }

  if (tif) {
    bool validDir = true;
    while (validDir) {
      // Directories are handled by the third dimension
      // If no directories are specified, progress as far
      // as needed to fill the dimensions provided.
      unsigned int imagelength, bitsPerSample;
      tdata_t buf;
      unsigned int row;
      unsigned int scanlinesize = TIFFScanlineSize(tif);

      shared_ptr<const XdmfArrayType> tiffDataType = array->getArrayType();

      TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bitsPerSample);

      TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &imagelength);

      if (compression == 1) {
        // Specific to non-compressed read

        if (bitsPerSample / 8 == 1) {
          tiffDataType = XdmfArrayType::UInt8();
        }
        else if (bitsPerSample / 8 == 2) {
          tiffDataType = XdmfArrayType::UInt16();
        }
        else if (bitsPerSample / 8 == 4) {
          tiffDataType = XdmfArrayType::UInt32();
        }

        // the buffer is a number of bytes equal to the scan line size
        buf = _TIFFmalloc(scanlinesize );

        scanlinesize /= array->getArrayType()->getElementSize();

        if (mDimensions.size() == 1)
        {
          if (sizeLeft == 0) {
            break;
          }
          // If there is one dimensions then we treat the entire entry as a single dataset.
          // We need to adjust the starting point accordingly.
          for (row = 0; row < imagelength; ++row)
          {
            TIFFReadScanline(tif, buf, row);
            unsigned int amountRead = sizeLeft;
            if ((scanlinesize - currentRowStart) / mStride[0] <= sizeLeft) {
              amountRead = (scanlinesize - currentRowStart) / mStride[0];
              if (scanlinesize % mStride[0] != 0 &&
                  currentRowStart % mStride[0] <= scanlinesize - (amountRead * mStride[0] + currentRowStart))
              {
                 amountRead++;
              }
            }
            readToArray(array,
                        buf,
                        amountWritten,
                        currentRowStart,
                        mStride[0],
                        amountRead,
                        tiffDataType);
            // check to see how the start matches up with the scanline size
            amountWritten += amountRead;
            if (sizeLeft == 0) {
              break;
            }

            if (amountRead < sizeLeft) {
              sizeLeft = sizeLeft - amountRead;
            }
            else {
              sizeLeft = 0;
            }
            if (((int)((amountRead * mStride[0]) + currentRowStart)) - scanlinesize >= 0)
            {
              currentRowStart = ((amountRead * mStride[0]) + currentRowStart) - scanlinesize;
            }
            else
            {
              currentRowStart = ((amountRead * (mStride[0] + 1)) + currentRowStart) - scanlinesize;
            }
          }
        }
        else {
        // Dimensions correspond to scanline size and number of scanlines
          unsigned int rowstride = mStride[1];
          unsigned int currentRowStart = mStart[0];
          for (row = mStart[1]; row < imagelength && row < mDataspaceDimensions[1]; row+=rowstride)
          {
            TIFFReadScanline(tif, buf, row);
            readToArray(array,
                        buf,
                        amountWritten,
                        currentRowStart,
                        mStride[0],
                        mDimensions[0],
                        tiffDataType);
            amountWritten += mDimensions[0];
          }
        }
        _TIFFfree(buf);

      }
      else if (compression == 5)
      {
        // In this case we need to use strips instead of scanlines
        // scanline size is in bytes when dealing with compression
        if (bitsPerSample == 1) {
          tiffDataType = XdmfArrayType::UInt8();
        }
        else if (bitsPerSample == 2) {
          tiffDataType = XdmfArrayType::UInt16();
        }
        else if (bitsPerSample == 4) {
          tiffDataType = XdmfArrayType::UInt32();
        }

        // the buffer is a number of bytes equal to the scan line size
        buf = _TIFFmalloc(TIFFStripSize(tif));

        scanlinesize /= array->getArrayType()->getElementSize();

        // For each strip in the directory
        for (unsigned int strip = 0; strip < TIFFNumberOfStrips(tif); strip++)
        {
          if (sizeLeft == 0) {
            break;
          }

          unsigned int currentStripSize = TIFFReadEncodedStrip(tif, strip, buf, -1);
          currentStripSize = currentStripSize / array->getArrayType()->getElementSize();
          // Size is in bits, and is not necessarily the same per strip
          unsigned int numberScanlines = currentStripSize / scanlinesize;
          // For the case of a partial scanline
          if (currentStripSize % scanlinesize != 0) {
            ++numberScanlines;
          }
          // If singledimensional
          // then write out the strip as if it was a scanline

          if (mDimensions.size() == 1)
          {
            unsigned int amountRead = sizeLeft;
            if ((currentStripSize - currentRowStart) / mStride[0] <= sizeLeft) {
              amountRead = (currentStripSize - currentRowStart) / mStride[0];
              if (currentStripSize % mStride[0] != 0 &&
                  currentRowStart % mStride[0] <= currentStripSize - (amountRead * mStride[0] + currentRowStart))
              {
                 amountRead++;
              }
            }
            readToArray(array,
                        buf,
                        amountWritten,
                        currentRowStart,
                        mStride[0],
                        amountRead,
                        tiffDataType);
            amountWritten += amountRead;
            if (sizeLeft == 0) {
              break;
            }

            if (amountRead < sizeLeft) {
              sizeLeft = sizeLeft - amountRead;
            }
            else {
              sizeLeft = 0;
            }
            if (((int)((amountRead * mStride[0]) + currentRowStart)) - currentStripSize >= 0)
            {
              currentRowStart = ((amountRead * mStride[0]) + currentRowStart) - currentStripSize;
            }
            else
            {
              currentRowStart = ((amountRead * (mStride[0] + 1)) + currentRowStart) - currentStripSize;
            }
          }
          else
          {
            currentRowStart = scanlineIndex;
            // If multidimensional
            // Loop through the scanlines in the strip
            for (; scanlineIndex < numberScanlines; scanlineIndex += mStride[1])
            {
              readToArray(array,
                          buf,
                          amountWritten,
                          currentRowStart,
                          mStride[0],
                          mDimensions[0],
                          tiffDataType);
              amountWritten += mDimensions[0];
              currentRowStart = currentRowStart + scanlinesize * mStride[1];
            }
            scanlineIndex = scanlineIndex % mStride[1];
          }
        }
      }

      if (mStride.size() >= 3)
      {
        currentDirectory += mStride[2];
      }
      else
      {
        ++currentDirectory;
      }

      validDir = TIFFSetDirectory(tif, currentDirectory);
    }
  }
  else {
    XdmfError::message(XdmfError::FATAL, "Error: Invalid TIFF file");
  }

  TIFFClose(tif);
}
Пример #24
0
static void run ( const gchar *name, gint nparams, const GimpParam *param,
                  gint *nreturn_vals, GimpParam **return_vals)
{
  static GimpParam values[3];
  GimpRunMode run_mode;
  GimpPDBStatusType status = GIMP_PDB_SUCCESS;
  SeparateContext mysc;
  //enum separate_function func = SEP_NONE;
  run_mode = param[0].data.d_int32;


  /* setup for localization */
  INIT_I18N ();

  cmsErrorAction( LCMS_ERROR_IGNORE );

  mysc.filename = NULL;
  if( nparams != ( run_mode == GIMP_RUN_NONINTERACTIVE ? 2 : 1 ) )
    status = GIMP_PDB_CALLING_ERROR;
  else if( run_mode == GIMP_RUN_NONINTERACTIVE ) {
    if( param[1].type != GIMP_PDB_STRING || strlen( param[1].data.d_string ) == 0 )
      status = GIMP_PDB_CALLING_ERROR;
    else
      mysc.filename = g_strdup( param[1].data.d_string );
  } else {
    gint size = gimp_get_data_size( "plug-in-separate-import/lastpath" );
    if( size ) {
      mysc.filename = g_malloc( size );
      gimp_get_data( "plug-in-separate-import/lastpath", mysc.filename );
    }
  }

  if( status == GIMP_PDB_SUCCESS && ( run_mode == GIMP_RUN_NONINTERACTIVE || separate_import_dialog( &mysc ) ) ) {
    gint i, j, x, y;
    TIFF *in;
    guint32 width, height, stripSize, stripCount, stripHeight;
    gint16 bps, spp, step, planerConfig, photometric, inkset, resolutionUnit;
    float xres, yres;
    const gchar *layerNames[] = { "C", "M", "Y", "K" };
    guchar *buf, *maskbuf[4], *srcbuf, *destbuf[4], *iccProfile;
    gint32 layers[5], masks[4];
    GimpDrawable *drw[4];
    GimpPixelRgn rgn[4];
    GimpRGB primaries[4] = { { .180, .541, .870, 1.0 },
                             { .925, .149, .388, 1.0 },
                             { .929, .862, .129, 1.0 },
                             { 0, 0, 0, 1.0 }  };

    gchar *str = NULL;
    gchar *baseName = g_path_get_basename( gimp_filename_to_utf8( mysc.filename ) );

#ifdef G_OS_WIN32
    {
      gchar *_filename = NULL; // win32 filename encoding(not UTF-8)
      _filename = g_win32_locale_filename_from_utf8( mysc.filename );
      in = TIFFOpen( _filename ? _filename : mysc.filename, "r" );
      g_free( _filename );
    }
#else
    in = TIFFOpen( mysc.filename, "r" );
#endif

    if( !in ) {
      str = g_strdup_printf( _( "Cannot open : \"%s\"" ), baseName );
      gimp_message( str );
      g_free( str );
      status = GIMP_PDB_EXECUTION_ERROR;
    } else {
      if( ( TIFFGetField( in, TIFFTAG_BITSPERSAMPLE, &bps ) == FALSE || ( bps != 8 && bps != 16 ) ) ||
          ( TIFFGetField( in, TIFFTAG_SAMPLESPERPIXEL, &spp ) == FALSE || spp != 4 ) ||
          ( TIFFGetField( in, TIFFTAG_PHOTOMETRIC, &photometric ) == FALSE || photometric != PHOTOMETRIC_SEPARATED ) ||
          ( TIFFGetField( in, TIFFTAG_PLANARCONFIG, &planerConfig ) == FALSE || planerConfig != PLANARCONFIG_CONTIG ) ||
          ( TIFFGetField( in, TIFFTAG_INKSET, &inkset ) == TRUE && inkset != INKSET_CMYK ) ) {
        str = g_strdup_printf( _( "\"%s\" is unsupported." ), baseName );
        gimp_message( str );
        g_free( str );
        status = GIMP_PDB_EXECUTION_ERROR;
      } else {
        stripCount = TIFFNumberOfStrips( in );
        stripSize = TIFFStripSize( in );
        TIFFGetField( in, TIFFTAG_IMAGEWIDTH, &width );
        TIFFGetField( in, TIFFTAG_IMAGELENGTH, &height );
        TIFFGetField( in, TIFFTAG_ROWSPERSTRIP, &stripHeight );
        TIFFGetField( in, TIFFTAG_RESOLUTIONUNIT, &resolutionUnit );
        TIFFGetField( in, TIFFTAG_XRESOLUTION, &xres );
        TIFFGetField( in, TIFFTAG_YRESOLUTION, &yres );

#if 0
        str = g_strdup_printf( "Photometric : %d  BPS : %d  SPP : %d\nInkset : %d  StripCount : %d", photometric, bps, spp, inkset, stripCount );
        gimp_message( str );
        g_free( str );
#endif

        step = ( bps == 16 ) ? 2 : 1;

        buf = g_malloc( stripSize );

        values[1].data.d_image = gimp_image_new( width, height, GIMP_RGB );
        gimp_image_set_resolution( values[1].data.d_image, xres, yres );
        gimp_context_push();
        for( i = 0; i < 4; i++ ) {
          layers[i] = gimp_layer_new( values[1].data.d_image, layerNames[i], width, height, GIMP_RGBA_IMAGE, 100.0, GIMP_DARKEN_ONLY_MODE );
          gimp_context_set_foreground( &primaries[i] );
          gimp_drawable_fill( layers[i], GIMP_FOREGROUND_FILL );
          gimp_image_add_layer( values[1].data.d_image, layers[i], i );
          masks[i] = gimp_layer_create_mask( layers[i], GIMP_ADD_BLACK_MASK );
          gimp_layer_add_mask( layers[i], masks[i] );
          drw[i] = gimp_drawable_get( masks[i] );
          maskbuf[i] = g_malloc( width * stripHeight );
        }
        gimp_context_pop();
        layers[4] = gimp_layer_new( values[1].data.d_image, _( "Background" ), width, height, GIMP_RGB_IMAGE, 100.0, GIMP_NORMAL_MODE );
        gimp_drawable_fill( layers[4], GIMP_WHITE_FILL );
        gimp_image_add_layer( values[1].data.d_image, layers[4], 4 );

        str = g_strdup_printf( _( "Reading \"%s\"..." ), baseName );
        gimp_progress_init( str );
        g_free( str );

        for( i = 0; i < stripCount; i++ ) {
          guint32 size = TIFFReadEncodedStrip( in, i, buf, stripSize );
          guint32 rowCount = ( size < stripSize ? height % stripHeight : stripHeight );
          srcbuf = buf;
          if( bps == 16 )
            srcbuf++;
          for( j = 0; j < 4; j++ ) {
            gimp_pixel_rgn_init( &( rgn[j] ), drw[j],
                                 0, stripHeight * i, width, rowCount,
                                 FALSE, FALSE );
            destbuf[j] = maskbuf[j];
          }
          for( y = 0; y < rowCount; y++ ) {
            for( x = 0; x < width; x++ ) {
              *destbuf[0]++ = *srcbuf;
              srcbuf += step;
              *destbuf[1]++ = *srcbuf;
              srcbuf += step;
              *destbuf[2]++ = *srcbuf;
              srcbuf += step;
              *destbuf[3]++ = *srcbuf;
              srcbuf += step;
              //srcbuf += spp > 4 ? spp - 4 : 0;
            }
          }
          gimp_pixel_rgn_set_rect( &( rgn[0] ), maskbuf[0], 0, stripHeight * i, width, rowCount );
          gimp_pixel_rgn_set_rect( &( rgn[1] ), maskbuf[1], 0, stripHeight * i, width, rowCount );
          gimp_pixel_rgn_set_rect( &( rgn[2] ), maskbuf[2], 0, stripHeight * i, width, rowCount );
          gimp_pixel_rgn_set_rect( &( rgn[3] ), maskbuf[3], 0, stripHeight * i, width, rowCount );
          gimp_progress_update( (gdouble)i / stripCount );
        }
        g_free( buf );
        for( i = 0; i < 4; i++ ) {
          g_free( maskbuf[i] );
          gimp_drawable_detach( drw[i] );
        }

#ifdef ENABLE_COLOR_MANAGEMENT
        if ( TIFFGetField( in, TIFFTAG_ICCPROFILE, &width, &iccProfile ) ) {
          GimpParasite *parasite;

          parasite = gimp_parasite_new( CMYKPROFILE, 0, width, iccProfile );
          gimp_image_parasite_attach( values[1].data.d_image, parasite );
          gimp_parasite_free( parasite );

          //g_free( iccProfile ); // This causes clash on TIFFClose( in ).
        }
#endif
      }
      TIFFClose( in );
    }
    g_free( baseName );
  } else
    status = GIMP_PDB_CANCEL;

  *return_vals = values;
  values[0].type = GIMP_PDB_STATUS;
  values[0].data.d_status = status;
  if( status == GIMP_PDB_SUCCESS ) {
    *nreturn_vals = 2;
    values[1].type = GIMP_PDB_IMAGE;
    if( run_mode != GIMP_RUN_NONINTERACTIVE ) {
      gimp_image_undo_enable( values[1].data.d_image );
      gimp_display_new( values[1].data.d_image );
      gimp_displays_flush();
    }
    gimp_set_data( "plug-in-separate-import/lastpath", mysc.filename, strlen( mysc.filename ) + 1 );
  } else
    *nreturn_vals = 1;

  g_free( mysc.filename );
}
Пример #25
0
int main(int argc, char **argv)
{
	int r, c;	// height index and width index
	
	struct tiff_info *info;	
	info = (struct tiff_info *)malloc(sizeof(struct tiff_info));
	
	uint16 *input_image;
	uint16 *output_image;
	uint16 *stripbuffer;	
	TIFF *input_file;
	int io_status;	// status of io operation
	
	/* according to tiffio library tsize_t is int32, tstrip_t is uint32 */	
	tsize_t strip_size, buffer_size;
	tstrip_t strip_max, strip_count, strip_num;
	unsigned long image_offset, result;
	unsigned long count;

	FILE *output_file;

	input_file = TIFFOpen(argv[1], "r");
	if(input_file == NULL){
		fprintf(stderr, "ERROR: Could not open input image!\n");
		exit(1);
	}
	printf("opening tiff file...\n");

	// input image paramters
	TIFFGetField(input_file, TIFFTAG_IMAGELENGTH, &info->length);
	TIFFGetField(input_file, TIFFTAG_IMAGEWIDTH, &info->width);
	TIFFGetField(input_file, TIFFTAG_BITSPERSAMPLE, &info->bps);
	TIFFGetField(input_file, TIFFTAG_SAMPLESPERPIXEL, &info->spp);
	TIFFGetField(input_file, TIFFTAG_PHOTOMETRIC, &info->photo_metric);
	
	printf("length = %d, width = %d\n", info->length, info->width);
	printf("bit per sample = %d\n", info->bps);
	printf("sample per pixel = %d\n", info->spp);
	printf("photo metirc is %d\n", info->photo_metric);

	// Read by multiple strips
	strip_size = TIFFStripSize (input_file);
	strip_max = TIFFNumberOfStrips (input_file);
	image_offset = 0;

	buffer_size = TIFFNumberOfStrips (input_file) * strip_size;
	
	printf("the strip_size is %u\n", strip_size);
	printf("the strip_max is %u\n", strip_max);
	printf("the image size if %u\n", buffer_size);
	printf("reading tif files...\n");

	if((stripbuffer = (uint16 *)_TIFFmalloc(buffer_size)) == NULL){
		fprintf(stderr, "Could not allocate enough memory for uncompressed image!\n");
		exit(42);
	}
	
	for (strip_count = 0; strip_count < strip_max; strip_count++){
		/*
		if((result = TIFFReadEncodedStrip( input_file, strip_count,
						stripbuffer + image_offset,
						strip_size)) == -1){
			fprintf(stderr, "reading error occurs on input strip number %d\n", strip_count);
			exit(42);
		}*/
		result = TIFFReadEncodedStrip( input_file, strip_count,
						stripbuffer + image_offset,
						strip_size);

		image_offset += result/2;
	}

	/*	
	if(info->photo_metric != PHOTOMETRIC_MINISWHITE){
		// Flip bits
		printf("Fixing the photometric interpretation\n");

		for(count = 0; count < buffer_size; count++)
		stripbuffer[count] = ~stripbuffer[count];
	}*/

	output_file = fopen("loaded_image_strip.dat", "w");

        for(count = 0; count < buffer_size/2; count++){
                fprintf(output_file, "%04x", (uint16) stripbuffer[count]);
                if((count + 1) % info->width == 0) fprintf(output_file, "\n");
                else fprintf(output_file, " ");
        }

        fclose(output_file);

	// _TIFFfree(input_image);
	_TIFFfree(stripbuffer);

	TIFFClose(input_file);	
	
	return 0;
}
Пример #26
0
RutSurface *
rut_surface_from_tiff_extents (const char *filename, RutExtents *extents)
{
  TIFF *tif = NULL;
  uint32 width, length, rows_per_strip;
  uint16 sample_format, bits_per_sample, samples_per_pixel;
  RutSurface *result = NULL;
  char *buffer = NULL;
  int i, j, row;

  int first_row, last_row, first_col, last_col;

  /* Open TIFF file */
  tif = TIFFOpen (filename, "rb");
  if (!tif) {
    goto loadfail;
  }

  /* Get standard tags */
  if (!(TIFFGetField (tif, TIFFTAG_IMAGEWIDTH, &width) &&
        TIFFGetField (tif, TIFFTAG_IMAGELENGTH, &length) &&
        TIFFGetField (tif, TIFFTAG_SAMPLEFORMAT, &sample_format) &&
        TIFFGetField (tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample) &&
        TIFFGetField (tif, TIFFTAG_SAMPLESPERPIXEL, &samples_per_pixel))) {
    goto loadfail;
  }

  /* Calculate extents of area of image to be loaded */
  first_row = 0;
  last_row = length - 1;
  first_col = 0;
  last_col = width - 1;
  if (extents) {
    first_row = MAX (extents->top, first_row);
    last_row = MIN (extents->height + extents->top, last_row);
    first_col = MAX (extents->left, first_col);
    last_col = MIN (extents->width + extents->left, last_col);
  }

  /* Validate compatibility */
  if (!TIFFGetField (tif, TIFFTAG_ROWSPERSTRIP, &rows_per_strip) ||
      (sample_format != SAMPLEFORMAT_IEEEFP) ||
      (bits_per_sample != 32) ||
      (samples_per_pixel != 1) ||
      TIFFIsTiled (tif)) {
    goto loadfail;
  }

  /* Create surface and allocate read buffer */
  result = rut_surface_new (length, width);
  buffer = malloc (TIFFStripSize (tif));

  /* Read data */
  for (i = 0, row = 0; i < TIFFNumberOfStrips (tif); i++) {
    size_t size = TIFFReadEncodedStrip (tif, i, buffer, TIFFStripSize (tif));
    int numrows = size/(width * 4);
    if (size % (width * 4) != 0) {
      /* Oops, not an integer number of rows! */
      goto loadfail;
    }

    for (j = 0; j < numrows; j++, row++) {
      if ((row < first_row) || (row > last_row)) continue;
      for (int col = 0; col < width; col++) {
        if ((col < first_col) || (col > last_col)) continue;
        union { char c[4]; float f; } val;
        char *src = &buffer[4 * (j * width + col)];
        memcpy (&val.c[0], src, 4);
        RUT_SURFACE_REF (result, row - first_row, col - first_col) = val.f;
      }
    }
  }

  /* Clean up */
  free (buffer);
  TIFFClose (tif);
  return result;

 loadfail:
  if (tif) TIFFClose (tif);
  if (buffer) free (buffer);
  if (result) rut_surface_destroy (result);
  fprintf (stderr, "Could not load TIFF from %s\n", filename);
  return NULL;
}
Пример #27
0
void
printTIF(TIFF* tif, uint16 pageNumber)
{
    uint32 w, h;
    uint16 unit, compression;
    float xres, yres, scale = 1.0;
    tstrip_t s, ns;
    time_t creation_time;

    TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
    TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
    if (!TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression)
	|| compression < COMPRESSION_CCITTRLE
	|| compression > COMPRESSION_CCITT_T6)
	return;
    if (!TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) || !xres) {
	TIFFWarning(TIFFFileName(tif),
	    "No x-resolution, assuming %g dpi", defxres);
	xres = defxres;
    }
    if (!TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) || !yres) {
	TIFFWarning(TIFFFileName(tif),
	    "No y-resolution, assuming %g lpi", defyres);
	yres = defyres;					/* XXX */
    }
    if (TIFFGetField(tif, TIFFTAG_RESOLUTIONUNIT, &unit) &&
      unit == RESUNIT_CENTIMETER) {
	xres *= 2.54F;
	yres *= 2.54F;
    }
    if (pageWidth == 0)
	pageWidth = w / xres;
    if (pageHeight == 0)
	pageHeight = h / yres;

    printf("%%!PS-Adobe-3.0\n");
    printf("%%%%Creator: fax2ps\n");
#ifdef notdef
    printf("%%%%Title: %s\n", file);
#endif
    creation_time = time(0);
    printf("%%%%CreationDate: %s", ctime(&creation_time));
    printf("%%%%Origin: 0 0\n");
    printf("%%%%BoundingBox: 0 0 %u %u\n",
	(int)(pageWidth * points), (int)(pageHeight * points));	/* XXX */
    printf("%%%%Pages: (atend)\n");
    printf("%%%%EndComments\n");
    printf("%%%%BeginProlog\n");
    emitFont(stdout);
    printf("/d{bind def}def\n"); /* bind and def proc */
    printf("/m{0 exch moveto}d\n");
    printf("/s{show}d\n");
    printf("/p{showpage}d \n");	/* end page */
    printf("%%%%EndProlog\n");
    printf("%%%%Page: \"%u\" %u\n", pageNumber, pageNumber);
    printf("/$pageTop save def gsave\n");
    if (scaleToPage)
        scale = pageHeight / (h/yres) < pageWidth / (w/xres) ?
            pageHeight / (h/yres) : pageWidth / (w/xres);
    printf("%g %g translate\n",
           points * (pageWidth - scale*w/xres) * half,
           points * (scale*h/yres + (pageHeight - scale*h/yres) * half));
    printf("%g %g scale\n", points/xres*scale, -points/yres*scale);
    printf("0 setgray\n");
    TIFFSetField(tif, TIFFTAG_FAXFILLFUNC, printruns);
    ns = TIFFNumberOfStrips(tif);
    row = 0;
    for (s = 0; s < ns; s++)
	(void) TIFFReadEncodedStrip(tif, s, (tdata_t) NULL, (tsize_t) -1);
    printf("p\n");
    printf("grestore $pageTop restore\n");
    totalPages++;
}
Пример #28
0
__declspec(dllexport) int AppendPage(int*& FileRef, double* DataArray, uint32 ImageHeight, uint32 ImageWidth, char* ImageType)
{
	uint16 SamplesPerPixel, BitsPerSample;
	uint8* DataArray_uint8 = (uint8*) DataArray;
	uint16* DataArray_uint16 = (uint16*)DataArray;
	int16* DataArray_int16 = (int16*)DataArray;
	uint32* DataArray_RGBA32 = (uint32*)DataArray;
	uint64* DataArray_RGBA64 = (uint64*)DataArray;
	float* DataArray_float32 = (float*)DataArray;
	tsize_t StripSize;
	uint32 rows;
	int nPixels = ImageWidth * ImageHeight;
	tstrip_t nStrips;


	if (!strcmp(ImageType, "uint8"))
	{
		BitsPerSample = 8;
		SamplesPerPixel = 1;
		DataArray_uint8 = new uint8[nPixels];
		for (int i = 0; i < nPixels; i++)
			DataArray_uint8[i] = (uint8)DataArray[i];
	}
	else if (!strcmp(ImageType, "uint16"))
	{
		BitsPerSample = 16;
		SamplesPerPixel = 1;
		DataArray_uint16 = new uint16[nPixels];
		for (int i = 0; i < nPixels; i++)
			DataArray_uint16[i] = (uint16)DataArray[i];
	}
	else if (!strcmp(ImageType, "int16"))
	{
		BitsPerSample = 16;
		SamplesPerPixel = 1;
		DataArray_int16 = new int16[nPixels];
		for (int i = 0; i < nPixels; i++)
			DataArray_int16[i] = (int16)DataArray[i];
	}
	else if (!strcmp(ImageType, "RGBA32"))
	{
		BitsPerSample = 8;
		SamplesPerPixel = 4;
		DataArray_RGBA32 = new uint32[nPixels];
		for (int i = 0; i < nPixels; i++)
			DataArray_RGBA32[i] = (uint32)DataArray[i];
	}
	else if (!strcmp(ImageType, "RGBA64"))
	{
		BitsPerSample = 16;
		SamplesPerPixel = 4;
		DataArray_RGBA64 = new uint64[nPixels];
		for (int i = 0; i < nPixels; i++)
			DataArray_RGBA64[i] = (uint64)DataArray[i];
	}
	else if (!strcmp(ImageType, "float32"))
	{
		BitsPerSample = 32;
		SamplesPerPixel = 1;
		DataArray_float32 = new float[nPixels];
		for (int i = 0; i < nPixels; i++)
			DataArray_float32[i] = (float)DataArray[i];
	}

	TIFF *tif = (TIFF*)FileRef;
	TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, ImageWidth);
	TIFFSetField(tif, TIFFTAG_IMAGELENGTH, ImageHeight);
	TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, SamplesPerPixel);
	TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, BitsPerSample);
	TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, 1); // black is zero
	TIFFSetField(tif, TIFFTAG_COMPRESSION, 5); // LZW compression

	rows = TIFFDefaultStripSize(tif, 0);
	TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rows);
	nStrips = TIFFNumberOfStrips(tif);
	StripSize = TIFFStripSize(tif);

	//  the code works fine for even number of rows. A proper handling of remainders should be introduced.
	// currently, the remainders are just not used.

	int striprows = (int)rows * (int)nStrips;
	if (striprows > (int)ImageHeight)
	{
		nStrips = nStrips - 1;
		TIFFSetField(tif, TIFFTAG_IMAGELENGTH, ImageHeight-1);
	}
	
	for (tstrip_t StripCount = 0; StripCount < nStrips; StripCount++)
	{
		if (!strcmp(ImageType, "uint8"))
			TIFFWriteEncodedStrip(tif, StripCount, &DataArray_uint8[StripCount * StripSize], StripSize);
		else if (!strcmp(ImageType, "uint16"))
			TIFFWriteEncodedStrip(tif, StripCount, &DataArray_uint16[(StripCount * StripSize)/2], StripSize);
		else if (!strcmp(ImageType, "int16"))
			TIFFWriteEncodedStrip(tif, StripCount, &DataArray_int16[(StripCount * StripSize)/2], StripSize);
		else if (!strcmp(ImageType, "RGBA32"))
			TIFFWriteEncodedStrip(tif, StripCount, &DataArray_RGBA32[(StripCount * StripSize)/4], StripSize);
		else if (!strcmp(ImageType, "RGBA64"))
			TIFFWriteEncodedStrip(tif, StripCount, &DataArray_RGBA64[(StripCount * StripSize)/4], StripSize);
		else if (!strcmp(ImageType, "float32"))
			TIFFWriteEncodedStrip(tif, StripCount, &DataArray_float32[(StripCount * StripSize)/4], StripSize);
	}
	
	TIFFRewriteDirectory(tif);
	
	if (!strcmp(ImageType, "uint8"))
	{
		delete[] DataArray_uint8;
	}
	else if (!strcmp(ImageType, "uint16"))
	{
		delete[] DataArray_uint16;
	}
	else if (!strcmp(ImageType, "int16"))
	{
		delete[] DataArray_int16;
	}
	else if (!strcmp(ImageType, "RGBA32"))
	{
		delete[] DataArray_RGBA32;
	}
	else if (!strcmp(ImageType, "RGBA64"))
	{
		delete[] DataArray_RGBA64;
	}
	else if (!strcmp(ImageType, "float32"))
	{
		delete [] DataArray_float32;
	}

	return 0;
}
Пример #29
0
__declspec(dllexport) int GetPage(int*& FileRef, double* DataArray, uint32& ImageHeight, uint32& ImageWidth, char* ImageType, int frameindex)
{
	TIFF *tif = (TIFF*)FileRef;
	tdir_t dirnumber = (tdir_t)frameindex;
	uint16 SamplesPerPixel, BitsPerSample;
	uint8* DataArray_uint8 = (uint8*)DataArray;
	uint16* DataArray_uint16 = (uint16*)DataArray;
	int16* DataArray_int16 = (int16*)DataArray;
	uint32* DataArray_RGBA32 = (uint32*)DataArray;
	uint64* DataArray_RGBA64 = (uint64*)DataArray;
	float* DataArray_float32 = (float*)DataArray;
	tsize_t StripSize;
	uint32 rows,W,H;
	int error;

	if (!TIFFSetDirectory(tif, dirnumber))
	{
		return 9001;
	}
	
	error = TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &W);
	error = TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &H);
	ImageWidth = W;
	ImageHeight = H;

	int nPixels = W * H;
	tstrip_t nStrips;

	if (!strcmp(ImageType, "uint8"))
	{
		BitsPerSample = 8;
		SamplesPerPixel = 1;
		DataArray_uint8 = new uint8[nPixels];
	}
	else if (!strcmp(ImageType, "uint16"))
	{
		BitsPerSample = 16;
		SamplesPerPixel = 1;
		DataArray_uint16 = new uint16[nPixels];
	}
	else if (!strcmp(ImageType, "int16"))
	{
		BitsPerSample = 16;
		SamplesPerPixel = 1;
		DataArray_int16 = new int16[nPixels];
	}
	else if (!strcmp(ImageType, "RGBA32"))
	{
		BitsPerSample = 8;
		SamplesPerPixel = 4;
		DataArray_RGBA32 = new uint32[nPixels];
	}
	else if (!strcmp(ImageType, "RGBA64"))
	{
		BitsPerSample = 16;
		SamplesPerPixel = 4;
		DataArray_RGBA64 = new uint64[nPixels];
	}
	else if (!strcmp(ImageType, "float32"))
	{
		BitsPerSample = 32;
		SamplesPerPixel = 1;
		DataArray_float32 = new float[nPixels];
	}

	error = TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rows);
	nStrips = TIFFNumberOfStrips(tif);
	StripSize = TIFFStripSize(tif);

	//  the code works fine for even number of rows. A proper handling of remainders should be introduced.
	// currently, the remainders are just not used. CHECK THIS STUFF FOR READING PURPOSES

	int striprows = (int)rows * (int)nStrips;
	if (striprows > (int)H)
	{
		nStrips = nStrips - 1;
		//TIFFSetField(tif, TIFFTAG_IMAGELENGTH, ImageHeight - 1);
	}

	for (tstrip_t StripCount = 0; StripCount < nStrips; StripCount++)
	{
		if (!strcmp(ImageType, "uint8"))
			error = TIFFReadEncodedStrip(tif, StripCount, &DataArray_uint8[StripCount * StripSize], StripSize);
		else if (!strcmp(ImageType, "uint16"))
			error = TIFFReadEncodedStrip(tif, StripCount, &DataArray_uint16[(StripCount * StripSize) / 2], StripSize);
		else if (!strcmp(ImageType, "int16"))
			error = TIFFReadEncodedStrip(tif, StripCount, &DataArray_int16[(StripCount * StripSize) / 2], StripSize);
		else if (!strcmp(ImageType, "RGBA32"))
			error = TIFFReadEncodedStrip(tif, StripCount, &DataArray_RGBA32[(StripCount * StripSize) / 4], StripSize);
		else if (!strcmp(ImageType, "RGBA64"))
			error = TIFFReadEncodedStrip(tif, StripCount, &DataArray_RGBA64[(StripCount * StripSize) / 4], StripSize);
		else if (!strcmp(ImageType, "float32"))
			error = TIFFReadEncodedStrip(tif, StripCount, &DataArray_float32[(StripCount * StripSize) / 4], StripSize);
	}

	if (!strcmp(ImageType, "uint8"))
	{
		for (int i = 0; i < nPixels; i++)
			DataArray[i] = (double)DataArray_uint8[i];
		//ImageHeight = (uint32)DataArray_uint8[51235];
		//ImageWidth = (uint32)DataArray[51235];
		delete[] DataArray_uint8;
	}
	else if (!strcmp(ImageType, "uint16"))
	{
		for (int i = 0; i < nPixels; i++)
			DataArray[i] = (double)DataArray_uint16[i];
		delete[] DataArray_uint16;
	}
	else if (!strcmp(ImageType, "int16"))
	{
		for (int i = 0; i < nPixels; i++)
			DataArray[i] = (double)DataArray_int16[i];
		delete[] DataArray_int16;
	}
	else if (!strcmp(ImageType, "RGBA32"))
	{
		for (int i = 0; i < nPixels; i++)
			DataArray[i] = (double)DataArray_RGBA32[i];
		delete[] DataArray_RGBA32;
	}
	else if (!strcmp(ImageType, "RGBA64"))
	{
		for (int i = 0; i < nPixels; i++)
			DataArray[i] = (double)DataArray_RGBA64[i];
		delete[] DataArray_RGBA64;
	}
	else if (!strcmp(ImageType, "float32"))
	{
		for (int i = 0; i < nPixels; i++)
			DataArray[i] = (double)DataArray_float32[i];
		delete[] DataArray_float32;
	}
	
	return error;
		
}
Пример #30
0
/*
 * Read the next TIFF directory from a file
 * and convert it to the internal format.
 * We read directories sequentially.
 */
int
TIFFReadDirectory(TIFF* tif)
{
	register TIFFDirEntry* dp;
	register int n;
	register TIFFDirectory* td;
	TIFFDirEntry* dir;
	int iv;
	long v;
	double dv;
	const TIFFFieldInfo* fip;
	int fix;
	uint16 dircount;
	toff_t nextdiroff;
	char* cp;
	int diroutoforderwarning = 0;

	tif->tif_diroff = tif->tif_nextdiroff;
	if (tif->tif_diroff == 0)		/* no more directories */
		return (0);
	/*
	 * Cleanup any previous compression state.
	 */
	(*tif->tif_cleanup)(tif);
	tif->tif_curdir++;
	nextdiroff = 0;
	if (!isMapped(tif)) {
		if (!SeekOK(tif, tif->tif_diroff)) {
			TIFFError(tif->tif_name,
			    "Seek error accessing TIFF directory");
			return (0);
		}
		if (!ReadOK(tif, &dircount, sizeof (uint16))) {
			TIFFError(tif->tif_name,
			    "Can not read TIFF directory count");
			return (0);
		}
		if (tif->tif_flags & TIFF_SWAB)
			TIFFSwabShort(&dircount);
		dir = (TIFFDirEntry *)CheckMalloc(tif,
		    dircount * sizeof (TIFFDirEntry), "to read TIFF directory");
		if (dir == NULL)
			return (0);
		if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) {
			TIFFError(tif->tif_name, "Can not read TIFF directory");
			goto bad;
		}
		/*
		 * Read offset to next directory for sequential scans.
		 */
		(void) ReadOK(tif, &nextdiroff, sizeof (uint32));
	} else {
		toff_t off = tif->tif_diroff;

		if (off + sizeof (uint16) > tif->tif_size) {
			TIFFError(tif->tif_name,
			    "Can not read TIFF directory count");
			return (0);
		} else
			_TIFFmemcpy(&dircount, tif->tif_base + off, sizeof (uint16));
		off += sizeof (uint16);
		if (tif->tif_flags & TIFF_SWAB)
			TIFFSwabShort(&dircount);
		dir = (TIFFDirEntry *)CheckMalloc(tif,
		    dircount * sizeof (TIFFDirEntry), "to read TIFF directory");
		if (dir == NULL)
			return (0);
		if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) {
			TIFFError(tif->tif_name, "Can not read TIFF directory");
			goto bad;
		} else
			_TIFFmemcpy(dir, tif->tif_base + off,
			    dircount*sizeof (TIFFDirEntry));
		off += dircount* sizeof (TIFFDirEntry);
		if (off + sizeof (uint32) <= tif->tif_size)
			_TIFFmemcpy(&nextdiroff, tif->tif_base+off, sizeof (uint32));
	}
	if (tif->tif_flags & TIFF_SWAB)
		TIFFSwabLong(&nextdiroff);
	tif->tif_nextdiroff = nextdiroff;

	tif->tif_flags &= ~TIFF_BEENWRITING;	/* reset before new dir */
	/*
	 * Setup default value and then make a pass over
	 * the fields to check type and tag information,
	 * and to extract info required to size data
	 * structures.  A second pass is made afterwards
	 * to read in everthing not taken in the first pass.
	 */
	td = &tif->tif_dir;
	/* free any old stuff and reinit */
	TIFFFreeDirectory(tif);
	TIFFDefaultDirectory(tif);
	/*
	 * Electronic Arts writes gray-scale TIFF files
	 * without a PlanarConfiguration directory entry.
	 * Thus we setup a default value here, even though
	 * the TIFF spec says there is no default value.
	 */
	TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);

	/*
	 * Sigh, we must make a separate pass through the
	 * directory for the following reason:
	 *
	 * We must process the Compression tag in the first pass
	 * in order to merge in codec-private tag definitions (otherwise
	 * we may get complaints about unknown tags).  However, the
	 * Compression tag may be dependent on the SamplesPerPixel
	 * tag value because older TIFF specs permited Compression
	 * to be written as a SamplesPerPixel-count tag entry.
	 * Thus if we don't first figure out the correct SamplesPerPixel
	 * tag value then we may end up ignoring the Compression tag
	 * value because it has an incorrect count value (if the
	 * true value of SamplesPerPixel is not 1).
	 *
	 * It sure would have been nice if Aldus had really thought
	 * this stuff through carefully.
	 */ 
	for (dp = dir, n = dircount; n > 0; n--, dp++) {
		if (tif->tif_flags & TIFF_SWAB) {
			TIFFSwabArrayOfShort(&dp->tdir_tag, 2);
			TIFFSwabArrayOfLong(&dp->tdir_count, 2);
		}
		if (dp->tdir_tag == TIFFTAG_SAMPLESPERPIXEL) {
			if (!TIFFFetchNormalTag(tif, dp))
				goto bad;
			dp->tdir_tag = IGNORE;
		}
	}
	/*
	 * First real pass over the directory.
	 */
	fix = 0;
	for (dp = dir, n = dircount; n > 0; n--, dp++) {

                /*
                 * Find the field information entry for this tag.
		 * Added check for tags to ignore ... [BFC]
                 */
		if( TIFFReassignTagToIgnore(TIS_EXTRACT, dp->tdir_tag) )
                    dp->tdir_tag = IGNORE;

		if (dp->tdir_tag == IGNORE)
                    continue;
                
		/*
		 * Silicon Beach (at least) writes unordered
		 * directory tags (violating the spec).  Handle
		 * it here, but be obnoxious (maybe they'll fix it?).
		 */
		if (dp->tdir_tag < tif->tif_fieldinfo[fix]->field_tag) {
			if (!diroutoforderwarning) {
				TIFFWarning(tif->tif_name,
	"invalid TIFF directory; tags are not sorted in ascending order");
				diroutoforderwarning = 1;
			}
			fix = 0;			/* O(n^2) */
		}
		while (fix < tif->tif_nfields &&
		    tif->tif_fieldinfo[fix]->field_tag < dp->tdir_tag)
			fix++;
		if (fix == tif->tif_nfields ||
		    tif->tif_fieldinfo[fix]->field_tag != dp->tdir_tag) {
			TIFFWarning(tif->tif_name,
			    "unknown field with tag %d (0x%x) ignored",
			    dp->tdir_tag,  dp->tdir_tag);
			dp->tdir_tag = IGNORE;
			fix = 0;			/* restart search */
			continue;
		}
		/*
		 * Null out old tags that we ignore.
		 */
		if (tif->tif_fieldinfo[fix]->field_bit == FIELD_IGNORE) {
	ignore:
			dp->tdir_tag = IGNORE;
			continue;
		}
		/*
		 * Check data type.
		 */
		fip = tif->tif_fieldinfo[fix];
		while (dp->tdir_type != (u_short) fip->field_type) {
			if (fip->field_type == TIFF_ANY)	/* wildcard */
				break;
			fip++, fix++;
			if (fix == tif->tif_nfields ||
			    fip->field_tag != dp->tdir_tag) {
				TIFFWarning(tif->tif_name,
				   "wrong data type %d for \"%s\"; tag ignored",
				    dp->tdir_type, fip[-1].field_name);
				goto ignore;
			}
		}
		/*
		 * Check count if known in advance.
		 */
		if (fip->field_readcount != TIFF_VARIABLE) {
			uint32 expected = (fip->field_readcount == TIFF_SPP) ?
			    (uint32) td->td_samplesperpixel :
			    (uint32) fip->field_readcount;
			if (!CheckDirCount(tif, dp, expected))
				goto ignore;
		}

		switch (dp->tdir_tag) {
		case TIFFTAG_COMPRESSION:
			/*
			 * The 5.0 spec says the Compression tag has
			 * one value, while earlier specs say it has
			 * one value per sample.  Because of this, we
			 * accept the tag if one value is supplied.
			 */
			if (dp->tdir_count == 1) {
				v = TIFFExtractData(tif,
				    dp->tdir_type, dp->tdir_offset);
				if (!TIFFSetField(tif, dp->tdir_tag, (int)v))
					goto bad;
				break;
			}
			if (!TIFFFetchPerSampleShorts(tif, dp, &iv) ||
			    !TIFFSetField(tif, dp->tdir_tag, iv))
				goto bad;
			dp->tdir_tag = IGNORE;
			break;
		case TIFFTAG_STRIPOFFSETS:
		case TIFFTAG_STRIPBYTECOUNTS:
		case TIFFTAG_TILEOFFSETS:
		case TIFFTAG_TILEBYTECOUNTS:
			TIFFSetFieldBit(tif, fip->field_bit);
			break;
		case TIFFTAG_IMAGEWIDTH:
		case TIFFTAG_IMAGELENGTH:
		case TIFFTAG_IMAGEDEPTH:
		case TIFFTAG_TILELENGTH:
		case TIFFTAG_TILEWIDTH:
		case TIFFTAG_TILEDEPTH:
		case TIFFTAG_PLANARCONFIG:
		case TIFFTAG_ROWSPERSTRIP:
			if (!TIFFFetchNormalTag(tif, dp))
				goto bad;
			dp->tdir_tag = IGNORE;
			break;
		case TIFFTAG_EXTRASAMPLES:
			(void) TIFFFetchExtraSamples(tif, dp);
			dp->tdir_tag = IGNORE;
			break;
		}
	}

	/*
	 * Allocate directory structure and setup defaults.
	 */
	if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
		MissingRequired(tif, "ImageLength");
		goto bad;
	}
	if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
		MissingRequired(tif, "PlanarConfiguration");
		goto bad;
	}
	/* 
 	 * Setup appropriate structures (by strip or by tile)
	 */
	if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) {
		td->td_nstrips = TIFFNumberOfStrips(tif);
		td->td_tilewidth = td->td_imagewidth;
		td->td_tilelength = td->td_rowsperstrip;
		td->td_tiledepth = td->td_imagedepth;
		tif->tif_flags &= ~TIFF_ISTILED;
	} else {
		td->td_nstrips = TIFFNumberOfTiles(tif);
		tif->tif_flags |= TIFF_ISTILED;
	}
	td->td_stripsperimage = td->td_nstrips;
	if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
		td->td_stripsperimage /= td->td_samplesperpixel;
	if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) {
		MissingRequired(tif,
		    isTiled(tif) ? "TileOffsets" : "StripOffsets");
		goto bad;
	}

	/*
	 * Second pass: extract other information.
	 */
	for (dp = dir, n = dircount; n > 0; n--, dp++) {
		if (dp->tdir_tag == IGNORE)
			continue;
		switch (dp->tdir_tag) {
		case TIFFTAG_MINSAMPLEVALUE:
		case TIFFTAG_MAXSAMPLEVALUE:
		case TIFFTAG_BITSPERSAMPLE:
			/*
			 * The 5.0 spec says the Compression tag has
			 * one value, while earlier specs say it has
			 * one value per sample.  Because of this, we
			 * accept the tag if one value is supplied.
			 *
			 * The MinSampleValue, MaxSampleValue and
			 * BitsPerSample tags are supposed to be written
			 * as one value/sample, but some vendors incorrectly
			 * write one value only -- so we accept that
			 * as well (yech).
			 */
			if (dp->tdir_count == 1) {
				v = TIFFExtractData(tif,
				    dp->tdir_type, dp->tdir_offset);
				if (!TIFFSetField(tif, dp->tdir_tag, (int)v))
					goto bad;
				break;
			}
			/* fall thru... */
		case TIFFTAG_DATATYPE:
		case TIFFTAG_SAMPLEFORMAT:
			if (!TIFFFetchPerSampleShorts(tif, dp, &iv) ||
			    !TIFFSetField(tif, dp->tdir_tag, iv))
				goto bad;
			break;
		case TIFFTAG_SMINSAMPLEVALUE:
		case TIFFTAG_SMAXSAMPLEVALUE:
			if (!TIFFFetchPerSampleAnys(tif, dp, &dv) ||
			    !TIFFSetField(tif, dp->tdir_tag, dv))
				goto bad;
			break;
		case TIFFTAG_STRIPOFFSETS:
		case TIFFTAG_TILEOFFSETS:
			if (!TIFFFetchStripThing(tif, dp,
			    td->td_nstrips, &td->td_stripoffset))
				goto bad;
			break;
		case TIFFTAG_STRIPBYTECOUNTS:
		case TIFFTAG_TILEBYTECOUNTS:
			if (!TIFFFetchStripThing(tif, dp,
			    td->td_nstrips, &td->td_stripbytecount))
				goto bad;
			break;
		case TIFFTAG_COLORMAP:
		case TIFFTAG_TRANSFERFUNCTION:
			/*
			 * TransferFunction can have either 1x or 3x data
			 * values; Colormap can have only 3x items.
			 */
			v = 1L<<td->td_bitspersample;
			if (dp->tdir_tag == TIFFTAG_COLORMAP ||
			    dp->tdir_count != (uint32) v) {
				if (!CheckDirCount(tif, dp, (uint32)(3*v)))
					break;
			}
			v *= sizeof (uint16);
			cp = CheckMalloc(tif, dp->tdir_count * sizeof (uint16),
			    "to read \"TransferFunction\" tag");
			if (cp != NULL) {
				if (TIFFFetchData(tif, dp, cp)) {
					/*
					 * This deals with there being only
					 * one array to apply to all samples.
					 */
					uint32 c =
					    (uint32)1 << td->td_bitspersample;
					if (dp->tdir_count == c)
						v = 0;
					TIFFSetField(tif, dp->tdir_tag,
					    cp, cp+v, cp+2*v);
				}
				_TIFFfree(cp);
			}
			break;
		case TIFFTAG_PAGENUMBER:
		case TIFFTAG_HALFTONEHINTS:
		case TIFFTAG_YCBCRSUBSAMPLING:
		case TIFFTAG_DOTRANGE:
			(void) TIFFFetchShortPair(tif, dp);
			break;
#ifdef COLORIMETRY_SUPPORT
		case TIFFTAG_REFERENCEBLACKWHITE:
			(void) TIFFFetchRefBlackWhite(tif, dp);
			break;
#endif
/* BEGIN REV 4.0 COMPATIBILITY */
		case TIFFTAG_OSUBFILETYPE:
			v = 0;
			switch (TIFFExtractData(tif, dp->tdir_type,
			    dp->tdir_offset)) {
			case OFILETYPE_REDUCEDIMAGE:
				v = FILETYPE_REDUCEDIMAGE;
				break;
			case OFILETYPE_PAGE:
				v = FILETYPE_PAGE;
				break;
			}
			if (v)
				(void) TIFFSetField(tif,
				    TIFFTAG_SUBFILETYPE, (int)v);
			break;
/* END REV 4.0 COMPATIBILITY */
		default:
			(void) TIFFFetchNormalTag(tif, dp);
			break;
		}
	}
	/*
	 * Verify Palette image has a Colormap.
	 */
	if (td->td_photometric == PHOTOMETRIC_PALETTE &&
	    !TIFFFieldSet(tif, FIELD_COLORMAP)) {
		MissingRequired(tif, "Colormap");
		goto bad;
	}
	/*
	 * Attempt to deal with a missing StripByteCounts tag.
	 */
	if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) {
		/*
		 * Some manufacturers violate the spec by not giving
		 * the size of the strips.  In this case, assume there
		 * is one uncompressed strip of data.
		 */
		if ((td->td_planarconfig == PLANARCONFIG_CONTIG &&
		    td->td_nstrips > 1) ||
		    (td->td_planarconfig == PLANARCONFIG_SEPARATE &&
		     td->td_nstrips != td->td_samplesperpixel)) {
		    MissingRequired(tif, "StripByteCounts");
		    goto bad;
		}
		TIFFWarning(tif->tif_name,
			"TIFF directory is missing required \"%s\" field, calculating from imagelength",
		    _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name);
		EstimateStripByteCounts(tif, dir, dircount);
#define	BYTECOUNTLOOKSBAD \
    ((td->td_stripbytecount[0] == 0 && td->td_stripoffset[0] != 0) || \
    (td->td_compression == COMPRESSION_NONE && \
     td->td_stripbytecount[0] > TIFFGetFileSize(tif) - td->td_stripoffset[0]))
	} else if (td->td_nstrips == 1 && BYTECOUNTLOOKSBAD) {
		/*
		 * Plexus (and others) sometimes give a value
		 * of zero for a tag when they don't know what
		 * the correct value is!  Try and handle the
		 * simple case of estimating the size of a one
		 * strip image.
		 */
		TIFFWarning(tif->tif_name,
	    "Bogus \"%s\" field, ignoring and calculating from imagelength",
		    _TIFFFieldWithTag(tif,TIFFTAG_STRIPBYTECOUNTS)->field_name);
		EstimateStripByteCounts(tif, dir, dircount);
	}
	if (dir)
		_TIFFfree((char *)dir);
	if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE))
		td->td_maxsamplevalue = (uint16)((1L<<td->td_bitspersample)-1);
	/*
	 * Setup default compression scheme.
	 */
	if (!TIFFFieldSet(tif, FIELD_COMPRESSION))
		TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
        /*
         * Some manufacturers make life difficult by writing
	 * large amounts of uncompressed data as a single strip.
	 * This is contrary to the recommendations of the spec.
         * The following makes an attempt at breaking such images
	 * into strips closer to the recommended 8k bytes.  A
	 * side effect, however, is that the RowsPerStrip tag
	 * value may be changed.
         */
	if (td->td_nstrips == 1 && td->td_compression == COMPRESSION_NONE &&
	    (tif->tif_flags & (TIFF_STRIPCHOP|TIFF_ISTILED)) == TIFF_STRIPCHOP)
		ChopUpSingleUncompressedStrip(tif);
	/*
	 * Reinitialize i/o since we are starting on a new directory.
	 */
	tif->tif_row = (uint32) -1;
	tif->tif_curstrip = (tstrip_t) -1;
	tif->tif_col = (uint32) -1;
	tif->tif_curtile = (ttile_t) -1;
	tif->tif_tilesize = TIFFTileSize(tif);
	tif->tif_scanlinesize = TIFFScanlineSize(tif);
	return (1);
bad:
	if (dir)
		_TIFFfree(dir);
	return (0);
}