Exemple #1
0
tdir_t tif_DirCount(TIFF* tif)
{
    tdir_t dirCurrent = TIFFCurrentDirectory(tif);
    int dirCount = 0;
    TIFFSetDirectory(tif, 0);
    do{
      dirCount++;
    }
    while(TIFFReadDirectory(tif));
    TIFFSetDirectory(tif, dirCurrent);
    return dirCount;
}
Exemple #2
0
static void
raster_special(int key, int x, int y)
{
        (void) x;
        (void) y;
        switch (key) {
                case GLUT_KEY_PAGE_UP:          /* previous logical image */
                    if (TIFFCurrentDirectory(tif) > 0) {
                            if (TIFFSetDirectory(tif,
                                                 TIFFCurrentDirectory(tif)-1)) {
                                    initImage();
                                    setWindowSize();
                        }
                    } else {
                            TIFFRGBAImageEnd(&img);
                            prevImage();
                            initImage();
                            setWindowSize();
                    }
                break;
                case GLUT_KEY_PAGE_DOWN:        /* next logical image */
                    if (!TIFFLastDirectory(tif)) {
                            if (TIFFReadDirectory(tif)) {
                                    initImage();
                                    setWindowSize();
                            }
                    } else {
                            TIFFRGBAImageEnd(&img);
                            nextImage();
                            initImage();
                            setWindowSize();
                    }
                break;
                case GLUT_KEY_HOME:             /* 1st image in current file */
                        if (TIFFSetDirectory(tif, 0)) {
                                TIFFRGBAImageEnd(&img);
                                initImage();
                                setWindowSize();
                        }
                break;
                case GLUT_KEY_END:              /* last image in current file */
                        TIFFRGBAImageEnd(&img);
                        while (!TIFFLastDirectory(tif))
                                TIFFReadDirectory(tif);
                        initImage();
                        setWindowSize();
                break;
        }
        glutPostRedisplay();
}
static bool paint_region(openslide_t *osr, cairo_t *cr,
                         int64_t x, int64_t y,
                         struct _openslide_level *level,
                         int32_t w, int32_t h,
                         GError **err) {
  struct generic_tiff_ops_data *data = osr->data;
  struct level *l = (struct level *) level;
  bool success = false;

  TIFF *tiff = _openslide_tiffcache_get(data->tc, err);
  if (tiff == NULL) {
    return false;
  }

  if (TIFFSetDirectory(tiff, l->tiffl.dir)) {
    success = _openslide_grid_paint_region(l->grid, cr, tiff,
                                           x / l->base.downsample,
                                           y / l->base.downsample,
                                           level, w, h,
                                           err);
  } else {
    g_set_error(err, OPENSLIDE_ERROR, OPENSLIDE_ERROR_FAILED,
                "Cannot set TIFF directory");
  }
  _openslide_tiffcache_put(data->tc, tiff);

  return success;
}
Exemple #4
0
void *image_read_tif(const char *name, int *w, int *h, int *c, int *b, int n)
{
    TIFF *T = 0;
    void *p = 0;

    TIFFSetWarningHandler(0);

    if ((T = TIFFOpen(name, "r")))
    {
        if ((n == 0) || TIFFSetDirectory(T, n))
        {
            uint32 i, s = (uint32) TIFFScanlineSize(T);
            uint32 W, H;
            uint16 B, C;

            TIFFGetField(T, TIFFTAG_IMAGEWIDTH,      &W);
            TIFFGetField(T, TIFFTAG_IMAGELENGTH,     &H);
            TIFFGetField(T, TIFFTAG_BITSPERSAMPLE,   &B);
            TIFFGetField(T, TIFFTAG_SAMPLESPERPIXEL, &C);

            if ((p = malloc(H * s)))
            {
                for (i = 0; i < H; ++i)
                    TIFFReadScanline(T, (uint8 *) p + i * s, i, 0);

                *w = (int) W;
                *h = (int) H;
                *b = (int) B / 8;
                *c = (int) C;
            }
        }
        TIFFClose(T);
    }
    return p;
}
Exemple #5
0
_declspec (dllexport) int readImage(TIFF* tif,              // TIFF handle - IN 
  const int directory,   // page ordinal number - IN
  uint8_t* redvals)      // OUT, caller allocates memory
{
  TIFFSetDirectory(tif, directory);
  int err = 0;
  uint32_t w, h;
  size_t npixels;

  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
  //TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, bits);
  npixels = w * h;
  uint32_t* raster = (uint32_t*) _TIFFmalloc(npixels * sizeof (uint32_t));
  if (raster != NULL) {
    err = TIFFReadRGBAImage(tif, w, h, raster, 1);
    if (err != 1) {
      return err;
    }
    uint32_t* pFrom = raster;
    uint8_t* pTo = redvals;
    for (int i = 0; i < npixels; i++, ++pFrom) {
      *pTo++ = (uint8_t) TIFFGetR(*pFrom);
    }
  }
  _TIFFfree(raster);
  return err;
}
Exemple #6
0
char *appendSlice2Tiff3DFile ( void *fhandler, int slice, unsigned char *img, unsigned int  img_width, unsigned int  img_height, int spp, int bpp, int NPages ) {
	TIFF *output = (TIFF *) fhandler;

	TIFFSetDirectory(output,slice); // WARNING: slice must be the first page after the last, otherwise the file can be corrupted

	TIFFSetField(output, TIFFTAG_IMAGEWIDTH, img_width);
	TIFFSetField(output, TIFFTAG_IMAGELENGTH, img_height);
	TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, (uint16)bpp); 
	TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, (uint16)spp);
	TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, img_height);
	TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_LZW);
	//TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
	TIFFSetField(output, TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
	TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);	
	//TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);	
	// We are writing single page of the multipage file 
	TIFFSetField(output, TIFFTAG_SUBFILETYPE, FILETYPE_PAGE);
	TIFFSetField(output, TIFFTAG_PAGENUMBER, (uint16)slice, (uint16)NPages); 

	TIFFWriteEncodedStrip(output, 0, img, img_width * img_height * spp * (bpp/8));
	//img +=  img_width * img_height;

	TIFFWriteDirectory(output);

	return (char *) 0;
}
Exemple #7
0
bool
TIFFInput::seek_subimage (int subimage, int miplevel, ImageSpec &newspec)
{
    if (subimage < 0)       // Illegal
        return false;
    if (m_emulate_mipmap) {
        // Emulating MIPmap?  Pretend one subimage, many MIP levels.
        if (subimage != 0)
            return false;
        subimage = miplevel;
    } else {
        // No MIPmap emulation
        if (miplevel != 0)
            return false;
    }

    if (subimage == m_subimage) {
        // We're already pointing to the right subimage
        newspec = m_spec;
        return true;
    }

    // If we're emulating a MIPmap, only resolution is allowed to change
    // between MIP levels, so if we already have a valid level in m_spec,
    // we don't need to re-parse metadata, it's guaranteed to be the same.
    bool read_meta = !(m_emulate_mipmap && m_tif && m_subimage >= 0);

    if (! m_tif) {
        // Use our own error handler to keep libtiff from spewing to stderr
        lock_guard lock (lasterr_mutex);
        TIFFSetErrorHandler (my_error_handler);
        TIFFSetWarningHandler (my_error_handler);
    }

    if (! m_tif) {
        m_tif = TIFFOpen (m_filename.c_str(), "rm");
        if (m_tif == NULL) {
            error ("Could not open file: %s",
                   lasterr.length() ? lasterr.c_str() : m_filename.c_str());
            return false;
        }
        m_subimage = 0;
    }
    
    m_next_scanline = 0;   // next scanline we'll read
    if (TIFFSetDirectory (m_tif, subimage)) {
        m_subimage = subimage;
        readspec (read_meta);
        newspec = m_spec;
        if (newspec.format == TypeDesc::UNKNOWN) {
            error ("No support for data format of \"%s\"", m_filename.c_str());
            return false;
        }
        return true;
    } else {
        error ("%s", lasterr.length() ? lasterr.c_str() : m_filename.c_str());
        m_subimage = -1;
        return false;
    }
}
Exemple #8
0
_declspec (dllexport) int readGreyImage(TIFF* tif,              // TIFF handle - IN 
  const int directory,   // page ordinal number - IN
  uint8_t* buffer)      // OUT, caller allocates memory
{
  TIFFSetDirectory(tif, directory);
  int err = 0;
  uint32_t w, h, s;
  size_t npixels;

  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
  s = TIFFScanlineSize(tif);
  //TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, bits);
  npixels = w * h;
  int numToRead = npixels / s;
  for (int r = 0; r < numToRead; r++)
  {
    err = TIFFReadScanline(tif, buffer+r*s, r);
    if (err != 1)
    {
      return -1*r;
    }
  }
  return err;
}
Exemple #9
0
static int close_tiff_output_file(t4_rx_state_t *s)
{
    int i;
    t4_rx_tiff_state_t *t;

    t = &s->tiff;
    /* Perform any operations needed to tidy up a written TIFF file before
       closure. */
    if (s->current_page > 1)
    {
        /* We need to edit the TIFF directories. Until now we did not know
           the total page count, so the TIFF file currently says one. Now we
           need to set the correct total page count associated with each page. */
        for (i = 0;  i < s->current_page;  i++)
        {
            TIFFSetDirectory(t->tiff_file, (tdir_t) i);
            TIFFSetField(t->tiff_file, TIFFTAG_PAGENUMBER, i, s->current_page);
            TIFFWriteDirectory(t->tiff_file);
        }
    }
    TIFFClose(t->tiff_file);
    t->tiff_file = NULL;
    if (s->tiff.file)
    {
        /* Try not to leave a file behind, if we didn't receive any pages to
           put in it. */
        if (s->current_page == 0)
            remove(s->tiff.file);
        free((char *) s->tiff.file);
    }
    s->tiff.file = NULL;
    return 0;
}
Exemple #10
0
char *appendSlice2Tiff3DFile ( void *fhandler, int slice, unsigned char *img, unsigned int  img_width, unsigned int  img_height, int spp, int bpp, int NPages ) {
	TIFF *output = (TIFF *) fhandler;

	TIFFSetDirectory(output,slice); // WARNING: slice must be the first page after the last, otherwise the file can be corrupted

	TIFFSetField(output, TIFFTAG_IMAGEWIDTH, img_width);
	TIFFSetField(output, TIFFTAG_IMAGELENGTH, img_height);
	TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, (uint16)bpp); 
	TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, (uint16)spp);
	TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, (rowsPerStrip == -1) ? img_height : rowsPerStrip);
	TIFFSetField(output, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
	TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_LZW);
	//TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
	TIFFSetField(output, TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
	TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);	
	//TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);	
	// We are writing single page of the multipage file 
	TIFFSetField(output, TIFFTAG_SUBFILETYPE, FILETYPE_PAGE);
	TIFFSetField(output, TIFFTAG_PAGENUMBER, (uint16)slice, (uint16)NPages); 

	if ( rowsPerStrip == -1 ) 
		TIFFWriteEncodedStrip(output, 0, img, img_width * img_height * spp * (bpp/8));
	else { 
		int check,StripsPerImage,LastStripSize;
		uint32 rps = rowsPerStrip;
		unsigned char *buf = img;

		StripsPerImage =  (img_height + rps - 1) / rps;
		LastStripSize = img_height % rps;
		if (LastStripSize==0)
			LastStripSize=rps;

		for (int i=0; i < StripsPerImage-1; i++){
			//if (comp==1) {
			//	TIFFReadRawStrip(input, i, buf, spp * rps * img_width * (bpp/8));
			//	buf = buf + spp * rps * img_width * (bpp/8);
			//}
			//else{
				TIFFWriteEncodedStrip(output, i, buf, spp * rps * img_width * (bpp/8));
				buf = buf + spp * rps * img_width * (bpp/8);
			//}
		}

		//if (comp==1) {
		//	TIFFReadRawStrip(input, StripsPerImage-1, buf, spp * LastStripSize * img_width * (bpp/8));
		//}
		//else{
			TIFFReadEncodedStrip(output, StripsPerImage-1, buf, spp * LastStripSize * img_width * (bpp/8));
		//}
		buf = buf + spp * LastStripSize * img_width * (bpp/8);
	}
	//img +=  img_width * img_height;

	TIFFWriteDirectory(output);

	return (char *) 0;
}
Exemple #11
0
    JNIEXPORT void JNICALL Java_com_troop_androiddng_RawToDng_WriteDNG(JNIEnv *env, jobject thiz, jobject handler)
    {
        uint64 dir_offset = 0, dir_offset2 = 0, gpsIFD_offset = 0;
        DngWriter* writer = (DngWriter*) env->GetDirectBufferAddress(handler);

        FILE* fptr = fopen(writer->fileSavePath,"w+");


        writeIfd0(fptr, writer);

        TIFFSetField (tif, TIFFTAG_EXIFIFD, dir_offset);
        LOGD("set exif");
        //CheckPOINT to KEEP EXIF IFD in MEMory
        //Try FiX DIR


        if(writer->gps == true)
        {
            makeGPS_IFD(tif, writer);
            TIFFCheckpointDirectory(tif);
            TIFFWriteCustomDirectory(tif, &gpsIFD_offset);
            TIFFSetDirectory(tif, 0);
        }


        writeExifIfd(tif,writer);
        //Check Point & Write are require checkpoint to update Current IFD Write Well to Write Close And Create IFD
        TIFFCheckpointDirectory(tif); //This Was missing it without it EXIF IFD was not being updated after adding SUB IFD
        TIFFWriteCustomDirectory(tif, &dir_offset);
        ///////////////////// GO Back TO IFD 0
        TIFFSetDirectory(tif, 0);
        if(writer->gps)
            TIFFSetField (tif, TIFFTAG_GPSIFD, gpsIFD_offset);
        ///////////////////////////// WRITE THE SUB IFD's SUB IFD + EXIF IFD AGain GPS IFD would also go here as well as other cust IFD
        TIFFSetField(tif, TIFFTAG_EXIFIFD, dir_offset);

        writeRawStuff(tif,writer);

        if (writer->bayerBytes == NULL)
            return;
        delete[] writer->bayerBytes;
        writer->bayerBytes = NULL;

    }
Exemple #12
0
bool
TIFFInput::seek_subimage (int subimage, int miplevel, ImageSpec &newspec)
{
    if (subimage < 0)       // Illegal
        return false;
    if (m_emulate_mipmap) {
        // Emulating MIPmap?  Pretend one subimage, many MIP levels.
        if (subimage != 0)
            return false;
        subimage = miplevel;
    } else {
        // No MIPmap emulation
        if (miplevel != 0)
            return false;
    }

    if (subimage == m_subimage) {
        // We're already pointing to the right subimage
        newspec = m_spec;
        return true;
    }

    if (! m_tif) {
        // Use our own error handler to keep libtiff from spewing to stderr
        lock_guard lock (lasterr_mutex);
        TIFFSetErrorHandler (my_error_handler);
        TIFFSetWarningHandler (my_error_handler);
    }

    if (! m_tif) {
        m_tif = TIFFOpen (m_filename.c_str(), "rm");
        if (m_tif == NULL) {
            error ("Could not open file: %s",
                   lasterr.length() ? lasterr.c_str() : m_filename.c_str());
            return false;
        }
        m_subimage = 0;
    }
    
    m_next_scanline = 0;   // next scanline we'll read
    if (TIFFSetDirectory (m_tif, subimage)) {
        m_subimage = subimage;
        readspec ();
        newspec = m_spec;
        if (newspec.format == TypeDesc::UNKNOWN) {
            error ("No support for data format of \"%s\"", m_filename.c_str());
            return false;
        }
        return true;
    } else {
        error ("%s", lasterr.length() ? lasterr.c_str() : m_filename.c_str());
        m_subimage = -1;
        return false;
    }
}
Exemple #13
0
_declspec (dllexport) void fixPageNumbers(const char* pathName, const int npages)
{
  TIFF* tif = TIFFOpen(pathName, "a8");
  TIFFSetDirectory(tif, 0);
  for (int i = 0; i < npages; i++)
  {
    TIFFSetField(tif, TIFFTAG_PAGENUMBER, i, npages);
    TIFFReadDirectory(tif);
  }
  TIFFClose(tif);
}
Exemple #14
0
      ome::compat::shared_ptr<IFD>
      TIFF::getDirectoryByIndex(directory_index_type index) const
      {
        Sentry sentry;

        if (!TIFFSetDirectory(impl->tiff, index))
          sentry.error();

        ome::compat::shared_ptr<TIFF> t(ome::compat::const_pointer_cast<TIFF>(shared_from_this()));
        return IFD::openIndex(t, index);
      }
Exemple #15
0
int
findPage(TIFF* tif, int pageNumber)
{
    uint16 pn = (uint16) -1;
    uint16 ptotal = (uint16) -1;
    if (GetPageNumber(tif)) {
	while (pn != pageNumber && TIFFReadDirectory(tif) && GetPageNumber(tif))
	    ;
	return (pn == pageNumber);
    } else
	return (TIFFSetDirectory(tif, pageNumber-1));
}
Exemple #16
0
int up(TIFF *T, int i)
{
    if (i < 6)
        return TIFFSetDirectory(T, i);
    else
    {
        if (up(T, face_parent(i)))
            return dn(T, face_index(i));
        else
            return 0;
    }
}
Exemple #17
0
/* tif load function */
int tif_load(uint16 *image)
{
	int r, c;	// height index, width index
	uint16 s;
	uint16 *scanline;
	long int image_offset;
	
	if((scanline = (uint16 *)_TIFFmalloc(info->line_size)) == NULL){
		fprintf(stderr, "Could not allocate enough memory for the scan buffer!\n");
		exit(42);
	}
	
	image_offset = 0;	
	printf("-- loading tif files ... \n");		

	TIFFSetDirectory(tif, 0);

	do {
		if (info->config == PLANARCONFIG_CONTIG){
			for(r = 0; r < info->length; r++){
				TIFFReadScanline(tif, scanline, r, s);

				for(c = 0; c < info->width; c++)
				{		
					image[image_offset + info->width * r + c] = *(scanline + c);
				}

			}
		} else if (info->config == PLANARCONFIG_SEPARATE){
			for(s = 0; s < info->spp; s++){
				for(r = 0; r < info->length; r++){
					TIFFReadScanline(tif, scanline, r, s);
					for(c = 0; c < info->width; c++)
					{
						image[image_offset + info->width * r + c] = *(scanline + c);
					}

				}
			}
		}
		image_offset += info->image_size/sizeof(uint16);
	} while (TIFFReadDirectory(tif));

	_TIFFfree(scanline);
	
	TIFFClose(tif);

	return 0;
}
Exemple #18
0
int get_tiff_total_pages(const char *file)
{
    TIFF *tiff_file;
    int max;

    if ((tiff_file = TIFFOpen(file, "r")) == NULL)
        return -1;
    /* Each page *should* contain the total number of pages, but can this be
       trusted? Some files say 0. Actually searching for the last page is
       more reliable. */
    max = 0;
    while (TIFFSetDirectory(tiff_file, (tdir_t) max))
        max++;
    TIFFClose(tiff_file);
    return max;
}
Exemple #19
0
static int write_tiff_image(t4_rx_state_t *s)
{
    t4_rx_tiff_state_t *t;
#if defined(SPANDSP_SUPPORT_TIFF_FX)
    uint64_t offset;
#endif

    t = &s->tiff;
    if (t->image_buffer == NULL  ||  t->image_size <= 0)
        return -1;
    /* Set up the TIFF directory info... */
    set_tiff_directory_info(s);
    /* ...Put the directory in the file before the image data, to get them in the order specified
       for TIFF/F files... */
    if (!TIFFCheckpointDirectory(t->tiff_file))
        span_log(&s->logging, SPAN_LOG_WARNING, "%s: Failed to checkpoint directory for page %d.\n", t->file, s->current_page);
    /* ...and write out the image... */
    if (TIFFWriteEncodedStrip(t->tiff_file, 0, t->image_buffer, t->image_size) < 0)
        span_log(&s->logging, SPAN_LOG_WARNING, "%s: Error writing TIFF strip.\n", t->file);
    /* ...then finalise the directory entry, and libtiff is happy. */
    if (!TIFFWriteDirectory(t->tiff_file))
        span_log(&s->logging, SPAN_LOG_WARNING, "%s: Failed to write directory for page %d.\n", t->file, s->current_page);
#if defined(SPANDSP_SUPPORT_TIFF_FX)
    if (s->current_page == 0)
    {
        if (!TIFFCreateCustomDirectory(t->tiff_file, &tiff_fx_field_array))
        {
            TIFFSetField(t->tiff_file, TIFFTAG_FAXPROFILE, PROFILETYPE_G3_FAX);
            TIFFSetField(t->tiff_file, TIFFTAG_PROFILETYPE, FAXPROFILE_F);
            TIFFSetField(t->tiff_file, TIFFTAG_VERSIONYEAR, "1998");

            offset = 0;
            if (!TIFFWriteCustomDirectory(t->tiff_file, &offset))
                printf("Failed to write custom directory.\n");

            /* Now go back and patch in the pointer to the new IFD */
            if (!TIFFSetDirectory(t->tiff_file, s->current_page))
                printf("Failed to set directory.\n");
            if (!TIFFSetField(t->tiff_file, TIFFTAG_GLOBALPARAMETERSIFD, offset))
                printf("Failed to set field.\n");
            if (!TIFFWriteDirectory(t->tiff_file))
                span_log(&s->logging, SPAN_LOG_WARNING, "%s: Failed to write directory for page %d.\n", t->file, s->current_page);
        }
    }
#endif
    return 0;
}
Exemple #20
0
char *appendSlice2Tiff3DFile ( char *filename, int slice, unsigned char *img, unsigned int img_width, unsigned int img_height ) {
    // 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods.
    #ifdef _VAA3D_TERAFLY_PLUGIN_MODE
    TERAFLY_TIME_START(TiffAppendData)
    #endif

	TIFF *output;
	uint16 spp, bpp, NPages, pg0;

	output=TIFFOpen(filename,"r");
	TIFFGetField(output, TIFFTAG_BITSPERSAMPLE, &bpp); 
	TIFFGetField(output, TIFFTAG_SAMPLESPERPIXEL, &spp);
	TIFFGetField(output, TIFFTAG_PAGENUMBER, &pg0, &NPages);
	TIFFClose(output);
	// since we are 
	output = (slice==0)? TIFFOpen(filename,"w") : TIFFOpen(filename,"a");

	TIFFSetDirectory(output,slice); // WARNING: slice must be the first page after the last, otherwise the file can be corrupted

	TIFFSetField(output, TIFFTAG_IMAGEWIDTH, img_width);
	TIFFSetField(output, TIFFTAG_IMAGELENGTH, img_height);
	TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, bpp); 
	TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, spp);
	TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, img_height);
	TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_LZW);
	//TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
	TIFFSetField(output, TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
	TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);	
	//TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);	
	// We are writing single page of the multipage file 
	TIFFSetField(output, TIFFTAG_SUBFILETYPE, FILETYPE_PAGE);
	TIFFSetField(output, TIFFTAG_PAGENUMBER, (uint16)slice, NPages); 

	TIFFWriteEncodedStrip(output, 0, img, img_width * img_height * spp * (bpp/8));
	//img +=  img_width * img_height;

	TIFFWriteDirectory(output);

	TIFFClose(output);

    // 2015-01-30. Alessandro. @ADDED performance (time) measurement in all most time-consuming methods.
    #ifdef _VAA3D_TERAFLY_PLUGIN_MODE
    TERAFLY_TIME_STOP(TiffAppendData, itm::IO, itm::strprintf("appended slice %d x %d to 3D tiff \"%s\"", img_width, img_height, filename))
    #endif

	return (char *) 0;
}
Exemple #21
0
_declspec (dllexport) void sinograph(TIFF* tif, const uint32_t slice, const int32_t w, const int32_t l, const int32_t total_quantity, int32_t samples_per_pixel, uint32_t used_quantity, const char* resultPath)
{
  if (slice >= (uint32_t) l)
  {
    return;
  }
  char pathName[1024];
  strcpy_s(pathName, resultPath);
  strcat_s(pathName, "\\sinograph.tif");

  TIFF* resultTif = makeTiffImage(pathName);
  TIFFSetField(resultTif, TIFFTAG_IMAGEWIDTH, w);
  TIFFSetField(resultTif, TIFFTAG_IMAGELENGTH, used_quantity);
  TIFFSetField(resultTif, TIFFTAG_BITSPERSAMPLE, 8);
  TIFFSetField(resultTif, TIFFTAG_SAMPLESPERPIXEL, samples_per_pixel);
  TIFFSetField(resultTif, TIFFTAG_ROWSPERSTRIP, 1);
  TIFFSetField(resultTif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  TIFFSetField(resultTif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);

  TIFFSetField(resultTif, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
  TIFFSetField(resultTif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
  int32_t scanlineSize = TIFFScanlineSize(tif);
  int32_t stripSize = TIFFStripSize(tif);
  int linesPerStrip = stripSize / scanlineSize;
  int stripOfInterest = slice / linesPerStrip; // keep integer division here
  int offsetPixels = slice % linesPerStrip * w;

  uint8_t* buffer = (uint8_t*) _TIFFmalloc(stripSize);

  int32_t selector = (total_quantity + used_quantity - 1) / used_quantity;
  used_quantity = 0;

  for (int32_t i = 0; i < total_quantity; i++)
  {
    if (i % selector != 0)
    {
      continue;
    }
    TIFFSetDirectory(tif, i);
    TIFFReadEncodedStrip(tif, stripOfInterest, buffer, stripSize);
    TIFFWriteScanline(resultTif, buffer + offsetPixels, used_quantity, scanlineSize);
    ++used_quantity;
  }

  _TIFFfree(buffer);
  TIFFClose(resultTif);
}
Exemple #22
0
unsigned char* HeightMipmap::readTile(int tx, int ty)
{
    char buf[256];
    unsigned char *data = new unsigned char[(tileSize + 5) * (tileSize + 5) * 2];
    int nTiles = max(1, (baseLevelSize / tileSize) >> (maxLevel - currentLevel));
    int nTilesPerFile = min(nTiles, 16);
    int dx = tx / nTilesPerFile;
    int dy = ty / nTilesPerFile;
    tx = tx % nTilesPerFile;
    ty = ty % nTilesPerFile;
    sprintf(buf, "%s/%.2d-%.4d-%.4d.tiff", cache.c_str(), currentLevel, dx, dy);
    TIFF* f = TIFFOpen(buf, "rb");
    TIFFSetDirectory(f, tx + ty * nTilesPerFile);
    TIFFReadEncodedStrip(f, 0, data, (tsize_t) -1);
    TIFFClose(f);
    return data;
}
Exemple #23
0
static image *image_reader(const char *name, int n)
{
    image *in = 0;
    TIFF  *T  = 0;
    int    f;

    if ((T = TIFFOpen(name, "r")))
    {
        if ((in = (image *) calloc(n, sizeof (image))))
        {
            for (f = 0; f < n; f++)
            {
                uint16 b, c, s = 0;
                uint32 w, h, r;
                float *p;

                TIFFSetDirectory(T, f);

                TIFFGetField(T, TIFFTAG_IMAGEWIDTH,      &w);
                TIFFGetField(T, TIFFTAG_IMAGELENGTH,     &h);
                TIFFGetField(T, TIFFTAG_SAMPLESPERPIXEL, &c);
                TIFFGetField(T, TIFFTAG_BITSPERSAMPLE,   &b);
                TIFFGetField(T, TIFFTAG_SAMPLEFORMAT,    &s);

                if ((p = (float *) malloc(h * w * c * sizeof (float))))
                {
                    for (r = 0; r < h; ++r)
                        TIFFReadFloatScanline(T, p + w * c * r, r);

                    in[f].p = (float *) p;
                    in[f].w = (int)     w;
                    in[f].h = (int)     h;
                    in[f].c = (int)     c;
                    in[f].b = (int)     b;
                    in[f].s = (int)     s;
                }
            }
        }
        TIFFClose(T);
    }
    return in;
}
Exemple #24
0
void imb_loadtiletiff(ImBuf *ibuf, unsigned char *mem, size_t size, int tx, int ty, unsigned int *rect)
{
	TIFF *image = NULL;
	uint32 width, height;
	ImbTIFFMemFile memFile;

	image = imb_tiff_client_open(&memFile, mem, size);

	if(image == NULL) {
		printf("imb_loadtiff: could not open TIFF IO layer for loading mipmap level.\n");
		return;
	}

   	if(TIFFSetDirectory(image, ibuf->miplevel)) {
		/* allocate the image buffer */
		TIFFGetField(image, TIFFTAG_IMAGEWIDTH,  &width);
		TIFFGetField(image, TIFFTAG_IMAGELENGTH, &height);

		if(width == ibuf->x && height == ibuf->y) {
			if(rect) {
				/* tiff pixels are bottom to top, tiles are top to bottom */
				if(TIFFReadRGBATile(image, tx*ibuf->tilex, (ibuf->ytiles - 1 - ty)*ibuf->tiley, rect) == 1) {
					if(ibuf->tiley > ibuf->y)
						memmove(rect, rect+ibuf->tilex*(ibuf->tiley - ibuf->y), sizeof(int)*ibuf->tilex*ibuf->y);

					if(ibuf->flags & IB_premul)
						IMB_premultiply_rect(rect, 32, ibuf->tilex, ibuf->tiley);
				}
				else
					printf("imb_loadtiff: failed to read tiff tile at mipmap level %d\n", ibuf->miplevel);
			}
		}
		else
			printf("imb_loadtiff: mipmap level %d has unexpected size %dx%d instead of %dx%d\n", ibuf->miplevel, width, height, ibuf->x, ibuf->y);
	}
	else
		printf("imb_loadtiff: could not find mipmap level %d\n", ibuf->miplevel);

	/* close the client layer interface to the in-memory file */
	TIFFClose(image);
}
Exemple #25
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);
}
Exemple #26
0
BOOL CImageTIFF::Read(FILE* stream)
{
	TIFF* m_tif = TIFFOpenEx(stream, "rb");

	uint32 height=0;
	uint32 width=0;
	uint16 bitspersample=1;
	uint16 samplesperpixel=1;
	uint32 rowsperstrip=-1;
	uint16 photometric=0;
	uint16 compression=1;
	uint32 x, y;
	BOOL isRGB;
	BYTE *bits;		//pointer to source data
	BYTE *bits2;	//pointer to destination data

  try{
	//check if it's a tiff file
	if (!m_tif)
		throw "Error encountered while opening TIFF file";

	m_info.nNumFrames=0;
	while(TIFFSetDirectory(m_tif,(uint16)m_info.nNumFrames)) m_info.nNumFrames++;


	if (!TIFFSetDirectory(m_tif, (uint16)m_info.nFrame))
		throw "Error: page not present in TIFF file";			

	//get image m_info
	TIFFGetField(m_tif, TIFFTAG_COMPRESSION, &compression);
	if (compression == COMPRESSION_LZW)
		throw "LZW compression is no longer supported due to Unisys patent enforcement";			

	TIFFGetField(m_tif, TIFFTAG_IMAGEWIDTH, &width);
	TIFFGetField(m_tif, TIFFTAG_IMAGELENGTH, &height);
	TIFFGetField(m_tif, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
	TIFFGetField(m_tif, TIFFTAG_BITSPERSAMPLE, &bitspersample);
	TIFFGetField(m_tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);   
	TIFFGetField(m_tif, TIFFTAG_PHOTOMETRIC, &photometric);

	m_header.biWidth  = width;
	m_header.biHeight = height;
	m_header.biClrUsed=0;
	m_info.nBkgndIndex =-1;

	isRGB = (bitspersample >= 8) &&
		(photometric == PHOTOMETRIC_RGB) ||
		(photometric == PHOTOMETRIC_YCBCR) ||
		(photometric == PHOTOMETRIC_SEPARATED) ||
		(photometric == PHOTOMETRIC_LOGLUV);

	if (isRGB){
		m_header.biBitCount=24;
		m_info.bColorType = COLORTYPE_COLOR;
	}else{
		m_info.bColorType = COLORTYPE_PALETTE;
		if ((photometric==PHOTOMETRIC_MINISBLACK)||(photometric==PHOTOMETRIC_MINISWHITE)){
			if	(bitspersample == 1){
				m_header.biBitCount=1;		//B&W image
				m_header.biClrUsed =2;
			} else {
				m_header.biBitCount=8;		//gray scale
				m_header.biClrUsed =256;
			}
		} else if (bitspersample == 4) {
			m_header.biBitCount=4;			// 16 colors
			m_header.biClrUsed=16;
		} else {
			m_header.biBitCount=8;			//256 colors
			m_header.biClrUsed=256;
		}
	}

	Create(m_header.biWidth,m_header.biHeight,m_header.biBitCount);	//image creation

	if (isRGB) {
		// Read the whole image into one big RGBA buffer using
		// the traditional TIFFReadRGBAImage() API that we trust.
		uint32* raster;		// retrieve RGBA image
		uint32 *row;

		raster = (uint32*)_TIFFmalloc(width * height * sizeof (uint32));
		if (raster == NULL) throw "No space for raster buffer";
			
		// Read the image in one chunk into an RGBA array
		if(!TIFFReadRGBAImage(m_tif, width, height, raster, 1)) {
				_TIFFfree(raster);
				throw "Corrupted TIFF file!";
		}

		// read the raster lines and save them in the DIB
		// with RGB mode, we have to change the order of the 3 samples RGB
		row = &raster[0];
		bits2 = m_info.pImage;
		for (y = 0; y < height; y++) {
			bits = bits2;
			for (x = 0; x < width; x++) {
				*bits++ = (BYTE)TIFFGetB(row[x]);
				*bits++ = (BYTE)TIFFGetG(row[x]);
				*bits++ = (BYTE)TIFFGetR(row[x]);
			}
			row += width;
			bits2 += m_info.dwEffWidth;
		}
		_TIFFfree(raster);
	} else {
		RGBQUAD *pal;
		pal=(RGBQUAD*)calloc(256,sizeof(RGBQUAD));
		if (pal==NULL) throw "Unable to allocate TIFF palette";

		// set up the colormap based on photometric	
		switch(photometric) {
			case PHOTOMETRIC_MINISBLACK:	// bitmap and greyscale image types
			case PHOTOMETRIC_MINISWHITE:
				if (bitspersample == 1) {	// Monochrome image
					if (photometric == PHOTOMETRIC_MINISBLACK) {
						pal[1].rgbRed = pal[1].rgbGreen = pal[1].rgbBlue = 255;
					} else {
						pal[0].rgbRed = pal[0].rgbGreen = pal[0].rgbBlue = 255;
					}
				} else {		// need to build the scale for greyscale images
					if (photometric == PHOTOMETRIC_MINISBLACK) {
						for (int i = 0; i < 256; i++) {
							pal[i].rgbRed = pal[i].rgbGreen = pal[i].rgbBlue = i;
						}
					} else {
						for (int i = 0; i < 256; i++) {
							pal[i].rgbRed =	pal[i].rgbGreen = pal[i].rgbBlue = 255 - i;
						}
					}
				}
				break;
			case PHOTOMETRIC_PALETTE:	// color map indexed
				uint16 *red;
				uint16 *green;
				uint16 *blue;
				TIFFGetField(m_tif, TIFFTAG_COLORMAP, &red, &green, &blue); 

				// Is the palette 16 or 8 bits ?
				BOOL Palette16Bits = FALSE;
				int n=1<<bitspersample;
				while (n-- > 0) {
					if (red[n] >= 256 || green[n] >= 256 || blue[n] >= 256) {
						Palette16Bits=TRUE;
						break;
					}
				}

				// load the palette in the DIB
				for (int i = (1 << bitspersample) - 1; i >= 0; i--) {
					if (Palette16Bits) {
						pal[i].rgbRed =(BYTE) CVT(red[i]);
						pal[i].rgbGreen = (BYTE) CVT(green[i]);
						pal[i].rgbBlue = (BYTE) CVT(blue[i]);           
					} else {
						pal[i].rgbRed = (BYTE) red[i];
						pal[i].rgbGreen = (BYTE) green[i];
						pal[i].rgbBlue = (BYTE) blue[i];        
					}
				}
				break;
		}
		SetPalette(pal,m_header.biClrUsed);	//palette assign
		free(pal);

		// read the tiff lines and save them in the DIB
		uint32 nrow;
		uint32 ys;
		int line = CalculateLine(width, bitspersample * samplesperpixel);
//		int pitch = CalculatePitch(line);
		long bitsize= TIFFStripSize(m_tif);
		bits = (BYTE*)malloc(bitsize);

		for (ys = 0; ys < height; ys += rowsperstrip) {
			nrow = (ys + rowsperstrip > height ? height - ys : rowsperstrip);
			if (TIFFReadEncodedStrip(m_tif, TIFFComputeStrip(m_tif, ys, 0), bits, nrow * line) == -1) {
				free(bits);
				throw "Corrupted TIFF file!";
			}
			for (y = 0; y < nrow; y++) {
				memcpy(m_info.pImage+m_info.dwEffWidth*(height-ys-nrow+y),bits+(nrow-y-1)*line,line);
			}
			/*if (m_header.biClrUsed==2){
				for (y = 0; y < nrow; y++) { for (x = 0; x < width; x++) {
					SetPixelIndex(x,y+ys,(bits[y*line+(x>>3)]>>(7-x%8))&0x01);
			}}}*/
		}
		free(bits);
	}
  } catch (char *message) {
	  strncpy(m_info.szLastError,message,255);
	  if (m_tif)	TIFFClose(m_tif);
	  return FALSE;
  }
	TIFFClose(m_tif);
	return TRUE;
}
Exemple #27
0
int
main(int argc, char* argv[])
{
	int c;
	int dirnum = -1;
	uint32 diroff = 0;

	oerror = TIFFSetErrorHandler(NULL);
	owarning = TIFFSetWarningHandler(NULL);
	while ((c = getopt(argc, argv, "d:o:p:eflmsvw?")) != -1)
	    switch (c) {
	    case 'd':
		dirnum = atoi(optarg);
		break;
	    case 'e':
		oerror = TIFFSetErrorHandler(oerror);
		break;
	    case 'l':
		order0 = FILLORDER_LSB2MSB;
		break;
	    case 'm':
		order0 = FILLORDER_MSB2LSB;
		break;
	    case 'o':
		diroff = strtoul(optarg, NULL, 0);
		break;
	    case 'p':
		photo0 = photoArg(optarg);
		break;
	    case 's':
		stoponerr = 1;
		break;
	    case 'w':
		owarning = TIFFSetWarningHandler(owarning);
		break;
	    case 'v':
		verbose = 1;
		break;
	    case '?':
		usage();
		/*NOTREACHED*/
	    }
	filenum = argc - optind;
	if ( filenum < 1)
	        usage();

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

	/*
	 * Get the screen size
	 */
	xmax = glutGet(GLUT_SCREEN_WIDTH);
	ymax = glutGet(GLUT_SCREEN_HEIGHT);

	/*
	 * Use 90% of the screen size
	 */
	xmax = xmax - xmax / 10.0;
	ymax = ymax - ymax / 10.0;

        filelist = (char **) _TIFFmalloc(filenum * sizeof(char*));
        if (!filelist) {
                TIFFError(argv[0], "Can not allocate space for the file list.");
                return 1;
        }
        _TIFFmemcpy(filelist, argv + optind, filenum * sizeof(char*));
	fileindex = -1;
	if (nextImage() < 0) {
		_TIFFfree(filelist);
		return 2;
	}
	/*
	 * Set initial directory if user-specified
	 * file was opened successfully.
	 */
	if (dirnum != -1 && !TIFFSetDirectory(tif, dirnum))
	    TIFFError(argv[0], "Error, seeking to directory %d", dirnum);
	if (diroff != 0 && !TIFFSetSubDirectory(tif, diroff))
	    TIFFError(argv[0], "Error, setting subdirectory at %#x", diroff);
	order = order0;
	photo = photo0;
	initImage();
	/*
	 * Create a new window or reconfigure an existing
	 * one to suit the image to be displayed.
	 */
	glutInitWindowSize(width, height);
	snprintf(title, 1024, "%s [%u]", filelist[fileindex],
		(unsigned int) TIFFCurrentDirectory(tif));
	glutCreateWindow(title);
	glutDisplayFunc(raster_draw);
	glutReshapeFunc(raster_reshape);
	glutKeyboardFunc(raster_keys);
	glutSpecialFunc(raster_special);
	glutMainLoop();

	cleanup_and_exit();
        return 0;
}
Exemple #28
0
main(int argc, char* argv[])
{
  //START;
  
  // the required page number in a multipage tiff, use 0 for first page
  int dir_num;
  dir_num = atoi(argv[2]);
  //time_t start, end;
  double duration;
  TIFF* tif = TIFFOpen(argv[1], "r");
  //get number of pages (Directories) in a tiff file
    int dir_count;
    dir_count = TIFFNumberOfDirectories(tif);
    if(dir_num < 0 || dir_num > (dir_count-1)){
       printf("Error: invalid directory number\n");
       exit -1;
    }
    else{
    
   if (tif) {
    uint32 w, h;
    size_t npixels;
    uint32* raster;
    // set the required page (directory)
    // change to the requested directory and read its contents with TIFFReadDirectory
    TIFFSetDirectory(tif,dir_num);
      
    TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
    TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
    npixels = w * h;

    int r,v;
    //Foreground and Background pixel values
    int F = 1, B = 0;
    size_t c_h, c_w;
    raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32));
    // image matrix with added boundary pixels
    int** I = malloc((h+2) * sizeof(int*));    // allocate the rows
    for ( r = 0; r < (h+2); ++r)
     {
       I[r] = malloc((w+2) * sizeof(int));    // allocate the columns
       //for ( cx = 0; cx < COLS; ++cx)
        // I[r][cx] = 0;
     }
     
     // an array of pixel runs (hashtable of pixel runs)
     // each run is a linked list of pixels
     struct pixel **runs = malloc((h*w/4) * sizeof(struct pixel));
     //initialise arrays and linked list
     for ( v = 0; v < (h*w/4); ++v)
     {
       //C[r] = r;    // initialise labels 
       init_pixel(runs[v], 99,99);
     }
     // arrays to save classes and their mappings
     //uint32* C = malloc((ROWS*COLS/2) * sizeof(uint32*)); 
     uint32* rl_table = malloc((h*w/4) * sizeof(uint32*)); 
     uint32* n_label = malloc((h*w/4) * sizeof(uint32*)); 
     uint32* t_label = malloc((h*w/4) * sizeof(uint32*));
     for ( v = 0; v < (h*w/4); ++v)
     {
       //C[r] = r;    
       // initialise classes
       rl_table[v] = v;  
       n_label[v] = -1;
       t_label[v] = v;      
     }
    
    // load image into matrix of F and B pixels (1's and 0's)
    if (raster != NULL) {
      if (TIFFReadRGBAImage(tif, w, h, raster, 0)) {          
        for(c_h=0;c_h<h;c_h++) {
           for(c_w=0;c_w<w;c_w++) {
              v = raster[(w*h)-((c_h*w)+(w-c_w))]%256;
              if (v == 0)
                I[c_h+1][c_w+1] = F;
              else
                I[c_h+1][c_w+1] = B;
           }          
        }               
      }
      _TIFFfree(raster);
    }
    
    /*
     c2  c3  c4
     c1  x 
    */
  

  // FIRST SCAN
  int i,j,k;
  int NewLabel=5; 

 int c1,c2,c3,c4,uu,vv,ii;
  for(c_h=1;c_h<(h-1);c_h++)
    for(c_w=1;c_w<(w-1);c_w++){ // for COLS
      if (I[c_h][c_w] == F) 
	{ 
	    c3 = I[c_h-1][c_w] ;
	    if (c3 != B) 
	    {
		I[c_h][c_w] = c3;
	    }
	    else // else1
	    {
	       c4 = I[c_h-1][c_w+1] ;
	       c1 = I[c_h][c_w-1] ;
	      if (c1 != B) 
	      {
		 I[c_h][c_w] = c1;
		 if (c4 != B && c4 != c1) 
		 {		  
		  //printf ("(%d,%d);", c1, c4);
		  //(* resolve c2 c4 *)	
		  uu = rl_table[c1]; vv = rl_table[c4];
		   if(uu<vv){
		        ii = vv;                      
                        while(ii != -1){
                          rl_table[ii] = uu;
                          ii = n_label[ii];
                        }                      
                        n_label[t_label[uu]] = vv;
                        t_label[uu] = t_label[vv];
		   }
		   else{
		      if(vv<uu){
		        ii = uu;                      
                        while(ii != -1){
                          rl_table[ii] = vv;
                          ii = n_label[ii];
                        }                      
                        n_label[t_label[vv]] = uu;
                        t_label[vv] = t_label[uu];
		      }
		   }		                     
		 }
	      }
	      else // else2
	      {
		 c2 = I[c_h-1][c_w-1] ;
		  if (c2 != B) 
		  {
		     I[c_h][c_w] = c2;
		      if (c4 != B && c4 != c2) 
		      {				               
			 //printf("(%d,%d);\n", c2, c4); 
		  	 //(* resolve c2 c4 *)
		 	 uu = rl_table[c2]; vv = rl_table[c4];
		         if(uu<vv){
	     	            ii = vv;                      
                            while(ii != -1){
                             rl_table[ii] = uu;
                             ii = n_label[ii];
                            }                      
                            n_label[t_label[uu]] = vv;
                            t_label[uu] = t_label[vv];
		         }
		         else{
		             if(vv<uu){
		                ii = uu;                      
                                while(ii != -1){
                                   rl_table[ii] = vv;
                                   ii = n_label[ii];
                                }                      
                               n_label[t_label[vv]] = uu;
                               t_label[vv] = t_label[uu];
		             }
		         }
			 
		     }
		  }
		  else 
		    if (c4 != B) 
		    {
			I[c_h][c_w] = c4;
		    }
		    else
		    {
			I[c_h][c_w] = NewLabel;
			NewLabel=NewLabel+1;
		    }
	       }// else2
	    }// else1
	}
  } // end for COLS
  
  // SECOND SCAN
  for(c_h=0;c_h<h;c_h++)
    for(c_w=0;c_w<w;c_w++) // for COLS
        if (I[c_h][c_w] != B)
          I[c_h][c_w] = rl_table[I[c_h][c_w]];
     
   
   
//get linked lists of pixels with the same class
//i.e. pixels that belong to the same CC
 for(c_h=0;c_h<h;c_h++){
   for(c_w=0;c_w<w;c_w++){
     if (I[c_h][c_w] != B)
     {       
       push(&runs[I[c_h][c_w]], c_w,c_h);
     }
  }
 }

 //now open a file, find coords of each CC and save them
 // char *base = get_basename(argv[1]);// = "filename";  
 char *base = argv[1];
  // find location of last '.' in filename to chop extension
  char *pos = strrchr (base, '.');
  int pos1 = pos ? (pos - base ) : -1;
  
  if(pos1 != -1){
    base[pos1] = 0; // remove file extension
    //printf("%d, %s\n",pos1, base);
  }

  //I'm assuming length of filename doesn't exceed 50 chars
  //I'll deal with this later
  char filename[256];
  
  
  FILE *file;
  //fname1[strlen(fname1) - 4] = 0; // remove file extension
  
  sprintf(filename, "%s-%d.json", base, dir_num);  
  
  //printf("%s\n", filename);
  
  file = fopen(filename,"w+");
  fprintf(file,"{\n");
  fprintf(file,"  \"SrcImage\": \"\",\n"); 
  fprintf(file,"  \"Page\": %d,\n",dir_num);
  fprintf(file,"  \"PageWidth\": %d,\n", w);
  fprintf(file,"  \"PageHeight\": %d,\n",h);
  fprintf(file,"  \"ClipX\": %d,\n",0);
  fprintf(file,"  \"ClipY\": %d,\n",0);
  fprintf(file,"  \"ClipWidth\": %d,\n", w);
  fprintf(file,"  \"ClipHeight\": %d,\n",h);  
  fprintf(file,"  \"ClipImage\": \"\",\n");
  fprintf(file,"  \"glyphs\": [\n");
  
  //count++;
  //file = fopen("file.txt","w+");
  int len;
   for ( v = 0; v < (h*w/4); ++v)
     {
       len = length(runs[v]); 
       if (len > 0 ){
         //printf("run ID: %d, run length %d\n", r, len );
         struct bbox* b = find_bbox (runs[v]);
         //printf("bbox: (%d,%d),(%d,%d)\n", b->x1, b->y1, b->x2, b->y2 );   
         fprintf(file,"    { \"x\" : %d, \"y\" : %d, \"w\" : %d, \"h\" : %d }",(b->x1-1),(b->y1-1), (b->x2 - b->x1 + 1), (b->y2 - b->y1 + 1)); 
	 fprintf(file, ",\n");
         free(runs[v]);// = NULL;
         free(b);
       }
    }
    // trick by Volker to remove comma after last glyph	 
   fseek(file, -( 2*(int)sizeof(char) ), SEEK_CUR);
   fprintf(file,"\n  ]\n");
   fprintf(file,"}\n");
   // close file
   fclose(file); 
   
   //printf("Generated: %s\n",filename);
   //manually free space allocated to various arrays and matrices
     for (v = 0; v < h; ++v)
     {
       free(I[v]);    // this frees the columns
     }
     free(I);    // this frees the rows
     free(runs);
     //free(C);
     free(rl_table);
     free(n_label);
     free(t_label);
 
    TIFFClose(tif);
  }//end if tif
  } //end else 
  //STOP;
  //PRINTTIME;
     
}
Exemple #29
0
toff_t GTIFFWriteDirectory(TIFF *hTIFF, int nSubfileType, int nXSize, int nYSize,
                           int nBitsPerPixel, int nPlanarConfig, int nSamples, 
                           int nBlockXSize, int nBlockYSize,
                           int bTiled, int nCompressFlag, int nPhotometric,
                           int nSampleFormat, 
                           int nPredictor,
                           unsigned short *panRed,
                           unsigned short *panGreen,
                           unsigned short *panBlue,
                           int nExtraSamples,
                           unsigned short *panExtraSampleValues,
                           const char *pszMetadata )

{
    toff_t	nBaseDirOffset;
    toff_t	nOffset;

    nBaseDirOffset = TIFFCurrentDirOffset( hTIFF );

#if defined(TIFFLIB_VERSION) && TIFFLIB_VERSION >= 20051201 /* 3.8.0 */
    TIFFFreeDirectory( hTIFF );
#endif

    TIFFCreateDirectory( hTIFF );
    
/* -------------------------------------------------------------------- */
/*      Setup TIFF fields.                                              */
/* -------------------------------------------------------------------- */
    TIFFSetField( hTIFF, TIFFTAG_IMAGEWIDTH, nXSize );
    TIFFSetField( hTIFF, TIFFTAG_IMAGELENGTH, nYSize );
    if( nSamples == 1 )
        TIFFSetField( hTIFF, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG );
    else
        TIFFSetField( hTIFF, TIFFTAG_PLANARCONFIG, nPlanarConfig );

    TIFFSetField( hTIFF, TIFFTAG_BITSPERSAMPLE, nBitsPerPixel );
    TIFFSetField( hTIFF, TIFFTAG_SAMPLESPERPIXEL, nSamples );
    TIFFSetField( hTIFF, TIFFTAG_COMPRESSION, nCompressFlag );
    TIFFSetField( hTIFF, TIFFTAG_PHOTOMETRIC, nPhotometric );
    TIFFSetField( hTIFF, TIFFTAG_SAMPLEFORMAT, nSampleFormat );

    if( bTiled )
    {
        TIFFSetField( hTIFF, TIFFTAG_TILEWIDTH, nBlockXSize );
        TIFFSetField( hTIFF, TIFFTAG_TILELENGTH, nBlockYSize );
    }
    else
        TIFFSetField( hTIFF, TIFFTAG_ROWSPERSTRIP, nBlockYSize );

    TIFFSetField( hTIFF, TIFFTAG_SUBFILETYPE, nSubfileType );

    if (panExtraSampleValues != NULL)
    {
        TIFFSetField(hTIFF, TIFFTAG_EXTRASAMPLES, nExtraSamples, panExtraSampleValues );
    }

    if ( nCompressFlag == COMPRESSION_LZW ||
         nCompressFlag == COMPRESSION_ADOBE_DEFLATE )
        TIFFSetField( hTIFF, TIFFTAG_PREDICTOR, nPredictor );

/* -------------------------------------------------------------------- */
/*	Write color table if one is present.				*/
/* -------------------------------------------------------------------- */
    if( panRed != NULL )
    {
        TIFFSetField( hTIFF, TIFFTAG_COLORMAP, panRed, panGreen, panBlue );
    }

/* -------------------------------------------------------------------- */
/*      Write metadata if we have some.                                 */
/* -------------------------------------------------------------------- */
    if( pszMetadata && strlen(pszMetadata) > 0 )
        TIFFSetField( hTIFF, TIFFTAG_GDAL_METADATA, pszMetadata );

/* -------------------------------------------------------------------- */
/*      Write directory, and return byte offset.                        */
/* -------------------------------------------------------------------- */
    if( TIFFWriteCheck( hTIFF, bTiled, "GTIFFWriteDirectory" ) == 0 )
    {
        TIFFSetSubDirectory( hTIFF, nBaseDirOffset );
        return 0;
    }

    TIFFWriteDirectory( hTIFF );
    TIFFSetDirectory( hTIFF, (tdir_t) (TIFFNumberOfDirectories(hTIFF)-1) );

    nOffset = TIFFCurrentDirOffset( hTIFF );

    TIFFSetSubDirectory( hTIFF, nBaseDirOffset );

    return nOffset;
}
Exemple #30
0
int main(int argc, char **argv)
{
	// clock_t start, end;
        struct timespec start, stop;
        double accum;

	int r, c;	// height index, width index
	uint16 s;
	int dircount = 0;
	
	struct tiff_info *info;	
	info = (struct tiff_info *)malloc(sizeof(struct tiff_info));
	
	uint32 data_size;
	unsigned long image_offset;
	//uint16 *input_image;
	uint16 *scanline;	
	TIFF *tif;

	// verify purpose
	uint32 count;
	FILE *output_file;	

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

	do {
		dircount++;
	} while (TIFFReadDirectory(tif));
	printf("%d images in %s\n", dircount, argv[1]);
	
	// input image paramters
	TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &info->length);
	TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &info->width);
	TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &info->bps);
	TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &info->spp);
	TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &info->photo_metric);
	TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &info->config);
		
	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 = %d\n", info->photo_metric);
	printf("planar config = %d\n", info->config);

	info->line_size = TIFFScanlineSize(tif);
	info->image_size = info->line_size * info->length;
	data_size = info->image_size * dircount;	

	if(info->spp != 1){
		info->spp = 1;
		printf("Warnning:sample per pixel value automatically set to 1!\n");
	}
	
	if((input_image = (uint16 *)_TIFFmalloc(data_size)) == NULL){
		fprintf(stderr, "Could not allocate enough memory for the uncompressed image!\n");
		exit(42);
	}

	if((scanline = (uint16 *)_TIFFmalloc(info->line_size)) == NULL){
		fprintf(stderr, "Could not allocate enough memory for the scan buffer!\n");
		exit(42);
	}
	
	image_offset = 0;
	printf("the line size is %d\n", info->line_size);
	printf("the image size is %d\n", info->image_size);
	printf("image offset is %ld\n", image_offset);
	printf("the total sequence image size is %d\n", data_size);
	printf("loading tif files ... \n");

	clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
	TIFFSetDirectory(tif, 0);

	do {
		if (info->config == PLANARCONFIG_CONTIG){
			for(r = 0; r < info->length; r++){
				TIFFReadScanline(tif, scanline, r, s);
			
				for(c = 0; c < info->width; c++)
				{		
					input_image[image_offset + info->width * r + c] = *(scanline + c);
				}
			}
		} else if (info->config == PLANARCONFIG_SEPARATE){
			for(s = 0; s < info->spp; s++){
				for(r = 0; r < info->length; r++){
					TIFFReadScanline(tif, scanline, r, s);
					for(c = 0; c < info->width; c++)
	                        	{
        	                        	input_image[image_offset + info->width * r + c] = *(scanline + c);
                	        	}
              			}
			}
		}
		image_offset += info->image_size/2;
	} while (TIFFReadDirectory(tif));
	printf("reading done.\n");

	clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &stop);
        accum = (stop.tv_sec - start.tv_sec)+(double)(stop.tv_nsec-start.tv_nsec)/(double)BILLION;
        printf("done in %lf second\n", accum);

	printf("writing to loadded_image_line.dat file...\n");
	output_file = fopen("loaded_image_line.dat", "w");

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

        fclose(output_file);
	printf("done!\n");
	
	_TIFFfree(input_image);
	_TIFFfree(scanline);

	TIFFClose(tif);	
	
	return 0;
}