Search code examples
iosipadtifflibtiff

TIFFOpen always return NULL in ios


I am trying to create TIFF image using Libtiff. I could not figure out the reason why the file is unable to be opened. Anyone have any idea??

TIFF *image;
// Open the TIFF file
if((image = TIFFOpen("output.tif", "w")) == NULL){
    printf("Could not open output.tif for writing\n");
}

Edit 1

#include <stdio.h>
#include <tiffio.h>

int main(int argc, char *argv[]){
// Define an image
char buffer[25 * 144] = { /* boring hex omitted */ };
TIFF *image;

// Open the TIFF file
if((image = TIFFOpen("output.tif", "w")) == NULL){
  printf("Could not open output.tif for writing\n");
exit(42);
}

// We need to set some values for basic tags before we can add any data
TIFFSetField(image, TIFFTAG_IMAGEWIDTH, 25 * 8);
TIFFSetField(image, TIFFTAG_IMAGELENGTH, 144);
TIFFSetField(image, TIFFTAG_BITSPERSAMPLE, 1);
TIFFSetField(image, TIFFTAG_SAMPLESPERPIXEL, 1);
TIFFSetField(image, TIFFTAG_ROWSPERSTRIP, 144);

TIFFSetField(image, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
TIFFSetField(image, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE);
TIFFSetField(image, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
TIFFSetField(image, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);

TIFFSetField(image, TIFFTAG_XRESOLUTION, 150.0);
TIFFSetField(image, TIFFTAG_YRESOLUTION, 150.0);
TIFFSetField(image, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);

// Write the information to the file
TIFFWriteEncodedStrip(image, 0, buffer, 25 * 144);

// Close the file
TIFFClose(image);
}

Any help will be appreciated. Thanks


Solution

  • You DO need a full path to access files on the wonderfully restricted iOS file system. You can only read and write files into your app's private directories. Each app has a unique area in the filesystem. The app's directory name is a long series of letters and numbers that can be queried with getenv(). Here's the C version:

    TIFF *image;
    char szFileName[512];
    
       strcpy(szFileName, getenv("HOME"));
       strcat(szFileName, "/Documents/");
       strcat(szFileName, "output.tif");
       // Open the TIFF file
       if((image = TIFFOpen(szFileName, "w")) == NULL)
       {
          printf("Could not open output.tif for writing\n");
       }
    

    Update: Since there may be some long term compatibility issues with this method, another option is to use argv[0] (the full path to your executable) and trim off the leaf name and modify it to point to the Documents directory.