Esempio n. 1
0
nitf_Record *readRecord(char *file)
{
    nitf_IOHandle in;            /* Handle for input */
    nitf_Reader *reader;         /* Reader object */
    nitf_Record *record;         /* The result */
    nitf_Error error;            /* For errors */

    in = nitf_IOHandle_create(file,
                              NITF_ACCESS_READONLY, NITF_OPEN_EXISTING, &error);
    if (NITF_INVALID_HANDLE(in))
    {
        nitf_Error_print(&error, stderr, "Error opening input ");
        exit(EXIT_FAILURE);
    }

    reader = nitf_Reader_construct(&error);
    if (!reader)
    {
        nitf_Error_print(&error, stderr, "Error creating reader ");
        exit(EXIT_FAILURE);
    }

    record = nitf_Reader_read(reader, in, &error);
    if (!record)
    {
        nitf_Error_print(&error, stderr, "Error reading input ");
        exit(EXIT_FAILURE);
    }

    nitf_IOHandle_close(in);
    nitf_Reader_destruct(&reader);
    return(record);
}
Esempio n. 2
0
void showExtSection(nitf_Extensions* ext)
{
    nitf_Error lerror;
    if (ext)
    {
        nitf_ExtensionsIterator extIter;
        nitf_ExtensionsIterator endIter;

        if ( nitf_Extensions_exists( ext, "AIMIDB" ) )
        {
            printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
            printf("DETECTED AIMIDB, REMOVING...\n");
            nitf_Extensions_removeTREsByName(ext, "AIMIDB");
            printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
        }

        extIter = nitf_Extensions_begin(ext);
        endIter = nitf_Extensions_end(ext);

        while (nitf_ExtensionsIterator_notEqualTo(&extIter, &endIter) )
        {
            nitf_TRE* tre = nitf_ExtensionsIterator_get(&extIter);
            if ( strcmp( tre->tag, "BLOCKA") == 0 )
            {
                printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
                printf("DETECTED SINGLE BLOCKA, REMOVING...\n");
                if ( (tre = nitf_Extensions_remove(ext, &extIter, &lerror)) == NULL)
                {
                    nitf_Error_print(&lerror, stdout, "Couldnt blow away blocka!\n");
                }

                printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
                printf("NOW RE-INSERTING BLOCK...\n");
                if (! nitf_Extensions_insert(ext, &extIter, tre, &lerror) )
                {
                    nitf_Error_print(&lerror, stdout, "Couldnt blow away blocka!\n");
                }
                printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");


            }
            /*printf("TRE: [%s]\n", tre->tag);
            showTRE(tre);*/
            nitf_ExtensionsIterator_increment(&extIter);
        }

        extIter = nitf_Extensions_begin(ext);
        endIter = nitf_Extensions_end(ext);

        while (nitf_ExtensionsIterator_notEqualTo(&extIter, &endIter) )
        {
            nitf_TRE* tre = nitf_ExtensionsIterator_get(&extIter);
            printf("TRE: [%s]\n", tre->tag);
            showTRE(tre);
            nitf_ExtensionsIterator_increment(&extIter);
        }

    }
}
Esempio n. 3
0
NITFPRIV(const char **) doInit(nitf_DLL * dll,
                               const char *prefix,
                               nitf_Error * error)
{
    NITF_PLUGIN_INIT_FUNCTION init;
    const char **ident;

    char name[NITF_MAX_PATH];
    memset(name, 0, NITF_MAX_PATH);
    NITF_SNPRINTF(name, NITF_MAX_PATH, "%s%s", prefix, NITF_PLUGIN_INIT_SUFFIX);
    init = (NITF_PLUGIN_INIT_FUNCTION) nitf_DLL_retrieve(dll, name, error);
    if (!init)
    {
        nitf_Error_print(error, stdout, "Invalid init hook in DSO");
        return NULL;
    }

    /*  Else, call it  */

    ident = (*init)(error);
    if (!ident)
    {
        nitf_Error_initf(error,
                         NITF_CTXT,
                         NITF_ERR_INVALID_OBJECT,
                         "The plugin [%s] is not retrievable", prefix);
        return NULL;
    }
    return ident;
}
Esempio n. 4
0
nitf_ImageSource *makeImageSource(
    test_nitf_ImageIOConstructArgs *args, char ***data)
{
    nitf_ImageSource *imgSource;  /* The result */
    nitf_Uint32 nBands;           /* Number of bands */
    nitf_Off bandSize;               /* Size of individual bands */
    nitf_Error error;             /* Error object argument */
    nitf_Uint32 i;

    bandSize = (args->nRows) * (args->nColumns) * (NITF_NBPP_TO_BYTES(args->nBits));

    imgSource = nitf_ImageSource_construct(&error);
    if (imgSource == NULL)
    {
        nitf_Error_print(&error, stderr, "Error setting up image source ");
        exit(EXIT_FAILURE);
    }

    nBands = args->nBands;
    if (nBands == 0)
        nBands = args->nMultiBands;

    for (i = 0;i < nBands;i++)
    {
        nitf_DataSource * bandSrc;   /* Current band data source */

        bandSrc = nitf_MemorySource_construct(
                      &(data[i][0][0]), bandSize, 0, 0, 0, &error);
        if (bandSrc == NULL)
        {
            nitf_Error_print(&error, stderr, "Error setting up band source ");
            exit(EXIT_FAILURE);
        }

        if (!nitf_ImageSource_addBand(imgSource, bandSrc, &error))
        {
            nitf_Error_print(&error, stderr, "Error setting up band source ");
            exit(EXIT_FAILURE);
        }

    }
    return(imgSource);
}
Esempio n. 5
0
nitf_ImageSource *setupBands(int nbands, int imageNum,
                             const char *inRootFile)
{
    nitf_Error error;
    int i;
    nitf_BandSource *bandSource;
    nitf_ImageSource *iSource = nitf_ImageSource_construct(&error);
    if (!iSource)
        goto CATCH_ERROR;
    for (i = 0; i < nbands; i++)
    {
        char *inFile = makeBandName(inRootFile, "img", imageNum, i);

        nitf_IOHandle sourceHandle =
            nitf_IOHandle_create(inFile, NITF_ACCESS_READONLY,
                                 NITF_OPEN_EXISTING, &error);
        if (NITF_INVALID_HANDLE(sourceHandle))
            goto CATCH_ERROR;
 
        freeBandName(&inFile);

        bandSource = nitf_FileSource_construct(sourceHandle,
                                               0, 0 /*gets ignored */ , 0,
                                               &error);
        freeBandName(&inFile);

        if (!bandSource)
        {
            goto CATCH_ERROR;
        }
        if (!nitf_ImageSource_addBand(iSource, bandSource, &error))
        {
            goto CATCH_ERROR;
        }
    }
    return iSource;

CATCH_ERROR:
    nitf_Error_print(&error, stderr, "While constructing image source");
    exit(EXIT_FAILURE);
}
Esempio n. 6
0
int main(int argc, char **argv)
{

    /*  This is the error we hopefully wont receive  */
    nitf_Error e;

    /* Skip factors */
    nitf_Uint32 rowSkipFactor = 1;
    nitf_Uint32 columnSkipFactor = 1;

    /*  This is the reader  */
    nitf_Reader *reader;

    /*  This is the record of the file we are reading  */
    nitf_Record *record;


    /*  This is the io handle we will give the reader to parse  */
    nitf_IOHandle io;

    int count = 0;
    int numImages;

    /*  These iterators are for going through the image segments  */
    nitf_ListIterator iter;
    nitf_ListIterator end;

    char* inputFile;
    NITF_BOOL optz = 0;

    /*  If you didnt give us a nitf file, we're croaking  */
    if (argc < 2)
    {
        printf("Usage: %s <nitf-file> (-o)\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (argc == 3)
    {
        optz = 1;

        if (strcmp(argv[1], "-o") == 0)
        {
            inputFile = argv[2];
        }
        else if (strcmp(argv[2], "-o") == 0)
        {
            inputFile = argv[1];
        }
        else
        {
            printf("Usage: %s <nitf-file> (-o)\n", argv[0]);
            exit(EXIT_FAILURE);

        }
    }
    else
        inputFile = argv[1];

    /*  You should use this function to test that you have a valid NITF */
    if (nitf_Reader_getNITFVersion( inputFile ) == NITF_VER_UNKNOWN)
    {
        printf("This file does not appear to be a valid NITF");
        exit(EXIT_FAILURE);
    }

    reader = nitf_Reader_construct(&e);
    if (!reader)
    {
        nitf_Error_print(&e, stderr, "Reader creation failed");
        exit(EXIT_FAILURE);
    }

    /*  
     *  As of 2.5, you do not have to use an IOHandle if you use 
     *  readIO instead of read()
     */
    io = nitf_IOHandle_create(inputFile,
                              NITF_ACCESS_READONLY,
                              NITF_OPEN_EXISTING, &e);

    if (NITF_INVALID_HANDLE(io))
    {
        nitf_Error_print(&e, stderr, "IO creation failed");
        exit(EXIT_FAILURE);
    }

    /*  Read the file  */
    record = nitf_Reader_read(reader, io, &e);
    if (!record)
    {
        nitf_Error_print(&e, stderr, "Read failed");
        nitf_IOHandle_close(io);
        nitf_Reader_destruct(&reader);
        exit(EXIT_FAILURE);
    }

    numImages = nitf_Record_getNumImages(record, &e);

    if ( NITF_INVALID_NUM_SEGMENTS( numImages ) )
    {
        nitf_Error_print(&e, stderr, "Failed to get the number of images");
        nitf_IOHandle_close(io);
        nitf_Reader_destruct(&reader);
        nitf_Record_destruct( &record );
        exit(EXIT_FAILURE);
    }

    /*  Set the iterator to traverse the list of image segments  */
    iter = nitf_List_begin(record->images);

    /*  And set this one to the end, so we'll know when we're done!  */
    end = nitf_List_end(record->images);

    for (count = 0; count < numImages; ++count)
    {
        nitf_ImageSegment *imageSegment =
            (nitf_ImageSegment *) nitf_ListIterator_get(&iter);

        nitf_ImageReader *deserializer =
            nitf_Reader_newImageReader(reader, count, &e);

        if (!deserializer)
        {
            nitf_Error_print(&e, stderr, "Couldnt spawn deserializer");
            exit(EXIT_FAILURE);
        }
        
        printf("Writing image %d... ", count);

        /*  Write the thing out  */
        writeImage(imageSegment, inputFile, deserializer, count,
                   rowSkipFactor, columnSkipFactor, optz, &e);

        nitf_ImageReader_destruct(&deserializer);
        
        printf("done.\n");

        /*  Increment the iterator so we can continue  */
        nitf_ListIterator_increment(&iter);
    }

    nitf_Record_destruct(&record);
    nitf_Reader_destruct(&reader);
    nitf_IOHandle_close(io);

    return 0;
}
Esempio n. 7
0
/* This test case just reads in a NITF file, clones it
 * then destructs the clone and original.
 * If you compile the library with the NITF_DEBUG flag set,
 * then you can make sure there are no memory leaks.
 *
 * In the future, we should use the cloned record to test
 * the functionality of a clone.
 */
int main(int argc, char **argv)
{
    /*  Get the error object       */
    nitf_Error     error;

    /*  This is the reader object  */
    nitf_Reader* reader;
    nitf_Record* record;
    nitf_Record* cloneRecord;

    /*  The IO handle  */
    nitf_IOHandle io;
    int num;

    /*  Check argv and make sure we are happy  */
    if ( argc != 2 )
    {
        printf("Usage: %s <nitf-file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    io = nitf_IOHandle_create(argv[1], NITF_ACCESS_READONLY, NITF_OPEN_EXISTING, &error);
    if ( NITF_INVALID_HANDLE( io ) )
    {
        nitf_Error_print(&error, stdout, "Exiting...");
        exit( EXIT_FAILURE );
    }

    reader = nitf_Reader_construct(&error);
    if (!reader)
    {
        nitf_Error_print(&error, stdout, "Exiting(1) ...");
        exit( EXIT_FAILURE );
    }

    /* read the record */
    record =  nitf_Reader_read(reader, io, &error  );
    if (!record) goto CATCH_ERROR;

    cloneRecord = nitf_Record_clone(record, &error);
    if (!cloneRecord)
    {
        nitf_Error_print(&error, stdout, "Exiting(3) ...");
        exit( EXIT_FAILURE );
    }

    printf("Destructing Cloned Record\n");
    nitf_Record_destruct(&cloneRecord);

    nitf_IOHandle_close(io);
    printf("Destructing Original Record\n");
    nitf_Record_destruct(&record);

    nitf_Reader_destruct(&reader);

    return 0;

CATCH_ERROR:
    printf("!!! we had a problem reading the file !!!\n");
    nitf_Error_print(&error, stdout, "Exiting...");
    exit(EXIT_FAILURE);
}
Esempio n. 8
0
int main(int argc, char *argv[])
{
    char *inFile;                 /* Input filename */
    char *outFile;                /* Output filename */
    char *compCode;               /* Compression code NC or NM */
    char *padValueString = NULL;  /* Pad value string */
    nitf_Reader *reader;          /* Reader object */
    nitf_Record *record;          /* Record used for input and output */
    imgInfo *imgs;                /* Image segment information */
    nitf_FileHeader *fileHdr;     /* File header */
    nitf_Uint32 numImages;        /* Total number of image segments */
    nitf_ListIterator imgIter;    /* Image segment list iterator */
    nitf_IOHandle in;             /* Input I/O handle */
    nitf_IOHandle out;            /* Output I/O handle */
    nitf_Writer *writer;          /* Writer object for output */
    static nitf_Error errorObj;   /* Error object for messages */
    nitf_Error *error;            /* Pointer to the error object */
    int i;

    error = &errorObj;

    compCode = "NM";
    if (argc == 3)
    {
        inFile = argv[1];
        outFile = argv[2];
    }
    else if (argc == 4)
    {
        if (strcmp(argv[1], "-r") != 0)
        {
            fprintf(stderr,
                    "Usage %s [-r] [-p padValue] inputFile outputFile\n", argv[0]);
            exit(EXIT_FAILURE);
        }
        inFile = argv[2];
        outFile = argv[3];
        compCode = "NC";
    }
    else if (argc == 5)
    {
        if (strcmp(argv[1], "-p") != 0)
        {
            fprintf(stderr,
                    "Usage %s [-r] [-p padValue] inputFile outputFile\n", argv[0]);
            exit(EXIT_FAILURE);
        }
        inFile = argv[3];
        outFile = argv[4];
        padValueString = argv[2];
    }
    else
    {
        fprintf(stderr, "Usage %s [-r] inputFile outputFile\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    /*    Get the input record */

    in = nitf_IOHandle_create(inFile,
                              NITF_ACCESS_READONLY, NITF_OPEN_EXISTING, error);
    if (NITF_INVALID_HANDLE(in))
    {
        nitf_Error_print(error, stderr, "Error opening input ");
        exit(EXIT_FAILURE);
    }

    reader = nitf_Reader_construct(error);
    if (!reader)
    {
        nitf_Error_print(error, stderr, "Error creating reader ");
        exit(EXIT_FAILURE);
    }

    record = nitf_Reader_read(reader, in, error);
    if (!record)
    {
        nitf_Error_print(error, stderr, "Error reading input ");
        exit(EXIT_FAILURE);
    }
    fileHdr = record->header;

    nitf_Field_get(fileHdr->numImages,
                   &numImages, NITF_CONV_UINT, NITF_INT32_SZ, error);

    /*  Get information about all image segments and set-up for write */

    imgs = (imgInfo *) NITF_MALLOC(numImages * sizeof(imgInfo));
    if (imgs == NULL)
    {
        nitf_Error_print(error, stderr, "Error allocating image info ");
        exit(EXIT_FAILURE);
    }

    for (i = 0;i < numImages;i++)
    {
        imgs[i].index = i;
        imgIter = nitf_List_at(record->images, i);
        imgs[i].seg = (nitf_ImageSegment *) nitf_ListIterator_get(&imgIter);
        if (!imgs[i].seg)
        {
            fprintf(stderr, "No Image segment in file\n");
            exit(EXIT_FAILURE);
        }
        imgs[i].subhdr = imgs[i].seg->subheader;

        if (padValueString != NULL)
        {
            if (!decodePadValue(&(imgs[i]), padValueString, imgs[i].padValue, error))
            {
                nitf_Error_print(error, stderr, "Error allocating image info ");
                exit(EXIT_FAILURE);
            }
        }
        else
            memset(imgs[i].padValue, 0, MAX_PAD);
    }

    /*   Read all of the image data into buffers */

    for (i = 0;i < numImages;i++)
        if (!readImageSegment(&(imgs[i]), reader, error))
        {
            nitf_Error_print(error, stderr, "Error reading image segment ");
            exit(EXIT_FAILURE);
        }

    /*  Set compression type to NM or NC (has to happen afetr read) */

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

        if (!nitf_ImageSubheader_setCompression(imgs[i].subhdr, compCode, "", error))
        {
            nitf_Error_print(error, stderr, "No DE segment in file ");
            exit(EXIT_FAILURE);
        }
    }

    /*   Create output */

    out = nitf_IOHandle_create(outFile, NITF_ACCESS_WRITEONLY, NITF_CREATE, error);
    if (NITF_INVALID_HANDLE(out))
    {
        nitf_Error_print(error, stderr, "Could not create output file ");
        exit(EXIT_FAILURE);
    }

    /*   Setup write and write */

    writer = nitf_Writer_construct(error);
    if (writer == NULL)
    {
        nitf_Error_print(error, stderr, "Write setup failed ");
        exit(EXIT_FAILURE);
    }

    if (!nitf_Writer_prepare(writer, record, out, error))
    {
        nitf_Error_print(error, stderr, "Write setup failed ");
        exit(EXIT_FAILURE);
    }

    for (i = 0;i < numImages;i++)
        if (!makeImageSource(&(imgs[i]), writer, error))
        {
            nitf_Error_print(error, stderr, "Write setup failed ");
            exit(EXIT_FAILURE);
        }

    /*  Set pad pixel if padValue string is not NULL */

    if (padValueString != NULL)
        for (i = 0;i < numImages;i++)
        {
        }

    if (!nitf_Writer_write(writer, error))
    {
        nitf_Error_print(error, stderr, "Write error ");
        exit(EXIT_FAILURE);
    }


    /*    Clean-up */

    nitf_Record_destruct(&record);
    nitf_IOHandle_close(out);
    return 0;

}
Esempio n. 9
0
int main(int argc, char **argv)
{
    nitf_Reader* reader;                /* The reader object */
    nitf_Writer* writer;                /* The writer object */
    nitf_Record* record;                /* a record object */
    nitf_Record* record2;
    nitf_ListIterator iter;             /* current pos iterator */
    nitf_ListIterator end;              /* end of list iterator */
    nitf_ImageSegment* segment;         /* the image segment */

    NITF_BOOL success;                  /* status bool */

    nitf_IOHandle input_io;             /* input IOHandle */
    nitf_IOHandle output_io;            /* output IOHandle */
    nitf_Error error;                   /* error object */

    /*  Check argv and make sure we are happy  */
    if (argc != 3)
    {
        printf("Usage: %s <input-file> <output-file> \n", argv[0]);
        exit(EXIT_FAILURE);
    }

    input_io = nitf_IOHandle_create(argv[1],
                                    NITF_ACCESS_READONLY,
                                    NITF_OPEN_EXISTING, &error);
    if ( NITF_INVALID_HANDLE(input_io))
    {
        goto CATCH_ERROR;
    }

    output_io = nitf_IOHandle_create(argv[2],
                                     NITF_ACCESS_WRITEONLY,
                                     NITF_CREATE | NITF_TRUNCATE,
                                     &error);

    if ( NITF_INVALID_HANDLE(output_io))
    {
        goto CATCH_ERROR;
    }

    reader = nitf_Reader_construct(&error);
    if (!reader)
    {
        goto CATCH_ERROR;
    }

    writer = nitf_Writer_construct(&error);
    if (!writer)
    {
        goto CATCH_ERROR;
    }

    record = nitf_Record_construct(&error);
    if (!record)
    {
        goto CATCH_ERROR;
    }

    assert(nitf_Reader_read(reader, input_io, record, &error));
    showFileHeader(record->header);

    /*  Write to the file  */
    success = nitf_Writer_writeHeader(writer, record->header, output_io, &error);
    if (!success) goto CATCH_ERROR;


    /*  ------ IMAGES ------  */
    iter = nitf_List_begin(record->images);
    end  = nitf_List_end(record->images);
    while (nitf_ListIterator_notEqualTo(&iter, &end))
    {
        /*  Cast it to an imageSegment...  */
        segment = (nitf_ImageSegment*)nitf_ListIterator_get(&iter);

        /* write the image subheader */
        if (!nitf_Writer_writeImageSubheader(writer,
                                             segment->subheader,
                                             record->header->NITF_FVER->raw,
                                             output_io,
                                             &error))
        {
            goto CATCH_ERROR;
        }

        /* Now, write the image */
        if (!writeImage(segment, input_io, output_io))
        {
            goto CATCH_ERROR;
        }

        nitf_ListIterator_increment(&iter);
    }

    nitf_IOHandle_close(input_io);
    nitf_IOHandle_close(output_io);
    nitf_Record_destruct(&record);
    nitf_Writer_destruct(&writer);

    /*  Open the file we just wrote to, and dump it to screen */
    input_io = nitf_IOHandle_create(argv[2],
                                    NITF_ACCESS_READONLY,
                                    NITF_OPEN_EXISTING,
                                    &error);
    if (NITF_INVALID_HANDLE(input_io))
    {
        goto CATCH_ERROR;
    }

    record2 = nitf_Record_construct(&error);
    if (!record2)
    {
        goto CATCH_ERROR;
    }

    assert(nitf_Reader_readHeader(reader, input_io, record2, &error));
    showFileHeader(record2->header);

    nitf_IOHandle_close(input_io);
    nitf_Record_destruct(&record2);
    nitf_Reader_destruct(&reader);

    return 0;

CATCH_ERROR:
    if (input_io) nitf_IOHandle_close(input_io);
    if (output_io) nitf_IOHandle_close(output_io);
    if (record2) nitf_Record_destruct(&record2);
    if (reader) nitf_Reader_destruct(&reader);
    if (record) nitf_Record_destruct(&record);
    if (writer) nitf_Writer_destruct(&writer);
    nitf_Error_print(&error, stdout, "Exiting...");
    exit(EXIT_FAILURE);
}
Esempio n. 10
0
int main(int argc, char **argv)
{
    /*  This is the reader object  */
    nitf_Reader* reader;
    nitf_Record*   record;
    /*  The IO handle  */
    nitf_IOHandle io;
    /*  Get the error object       */
    nitf_Error     error;

    /*  Check argv and make sure we are happy  */
    if ( argc != 2 )
    {
        printf("Usage: %s <nitf-file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    io = nitf_IOHandle_create(argv[1],
                              NITF_ACCESS_READONLY,
                              NITF_OPEN_EXISTING,
                              &error);
    if ( NITF_INVALID_HANDLE( io ) )
    {
        nitf_Error_print(&error, stdout, "Exiting...");
        exit( EXIT_FAILURE );
    }

    reader = nitf_Reader_construct(&error);
    if (!reader)
    {
        nitf_Error_print(&error, stdout, "Exiting (1) ...");
        exit( EXIT_FAILURE );
    }

    printf("Here are the loaded handlers\n");
    printf("* * * * * * * * * * * * * * * *\n");
    {
        nitf_PluginRegistry* reg = nitf_PluginRegistry_getInstance(&error);
        nitf_HashTable_print( reg->treHandlers);
    }
    printf("* * * * * * * * * * * * * * * *\n");

    record = nitf_Reader_read(reader, io, &error);
    if (!record)
    {
        nitf_Error_print(&error, stderr, "Failed to read the file");
        exit(EXIT_FAILURE);

    }

    /* Now show the header */
    showFileHeader(record->header);

    /* And now show the image information */
    if (record->header->numImages)
    {

        /*  Walk each image and show  */
        nitf_ListIterator iter = nitf_List_begin(record->images);
        nitf_ListIterator end  = nitf_List_end(record->images);

        while ( nitf_ListIterator_notEqualTo(&iter, &end) )
        {
            nitf_ImageSegment* segment =
                (nitf_ImageSegment*)nitf_ListIterator_get(&iter);

            nitf_ImageSubheader* dolly =
                nitf_ImageSubheader_clone(segment->subheader, &error);
            if (!dolly)
            {
                nitf_Error_print(&error, stdout, "During cloning!");
                exit(EXIT_FAILURE);
            }

            SHOW_IMSUB(segment->subheader);
            SHOW_IMSUB(dolly);

            nitf_ImageSubheader_destruct(&dolly);

            nitf_ListIterator_increment(&iter);

        }
    }
    else
    {
        printf("No image in file!\n");
    }

    nitf_IOHandle_close(io);
    nitf_Record_destruct(&record);
    nitf_Reader_destruct(&reader);

    return 0;
}
Esempio n. 11
0
int main(int argc, char *argv[])
{
    nitf_Reader *reader;        /* Reader object */
    nitf_Record *record;        /* Record used for input and output */
    nitf_IOHandle in;           /* Input I/O handle */
    nitf_ListIterator desIter;  /* Iterator for getting the DES */
    nitf_DESegment *des;        /* DE segment to read */
    nitf_DEReader *deReader;    /* DE reader object for reading data */
    char *data;                 /* Data buffer */
    static nitf_Error errorObj; /* Error object for messages */
    nitf_Error *error;          /* Pointer to the error object */

    error = &errorObj;

    if (argc != 2)
    {
        fprintf(stderr, "Usage %s inputFile\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    /*    Get the input record */

    in = nitf_IOHandle_create(argv[1],
                              NITF_ACCESS_READONLY, NITF_OPEN_EXISTING,
                              error);
    if (NITF_INVALID_HANDLE(in))
    {
        nitf_Error_print(error, stderr, "Error opening input ");
        exit(EXIT_FAILURE);
    }

    reader = nitf_Reader_construct(error);
    if (!reader)
    {
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Error creating reader ");
        exit(EXIT_FAILURE);
    }

    record = nitf_Reader_read(reader, in, error);
    if (!record)
    {
        nitf_Reader_destruct(&reader);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Error reading input ");
        exit(EXIT_FAILURE);
    }

    /*    Print the user header */

    desIter = nitf_List_at(record->dataExtensions, 0);
    des = (nitf_DESegment *) nitf_ListIterator_get(&desIter);
    if (!des)
    {
        nitf_Reader_destruct(&reader);
        nitf_Record_destruct(&record);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "No DE segment in file ");
        exit(EXIT_FAILURE);
    }

    nitf_TRE_print(des->subheader->subheaderFields, error);

    /*    Read the data and print it */

    deReader = nitf_Reader_newDEReader(reader, 0, error);
    if (!deReader)
    {
        nitf_Reader_destruct(&reader);
        nitf_Record_destruct(&record);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Could not create DEReader ");
        exit(EXIT_FAILURE);
    }

    fprintf(stdout, "Data length = %d\n", deReader->user->dataLength);
    fprintf(stdout, "Virtual data length = %d\n",
            deReader->user->virtualLength);
    fprintf(stdout, "File offset = %lld\n", deReader->user->baseOffset);

    data = (char *) NITF_MALLOC(deReader->user->virtualLength + 2);
    if (!data)
    {
        nitf_DEReader_destruct(&deReader);
        nitf_Reader_destruct(&reader);
        nitf_Record_destruct(&record);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Could not allocate data buffer ");
        exit(EXIT_FAILURE);
    }

    if (!nitf_DEReader_read
            (deReader, data, deReader->user->virtualLength, error))
    {
        NITF_FREE(data);
        nitf_DEReader_destruct(&deReader);
        nitf_Reader_destruct(&reader);
        nitf_Record_destruct(&record);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Read failed ");
        exit(EXIT_FAILURE);
    }

    fprintf(stdout, "Data: |%s|\n", data);

    /*    Try some seeks */

    if (nitf_DEReader_seek(deReader, (nitf_Off) 4, SEEK_SET, error) == (nitf_Off) - 1)
    {
        NITF_FREE(data);
        nitf_DEReader_destruct(&deReader);
        nitf_Reader_destruct(&reader);
        nitf_Record_destruct(&record);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Read failed ");
        exit(EXIT_FAILURE);
    }

    if (!nitf_DEReader_read(deReader, data, 1, error))
    {
        NITF_FREE(data);
        nitf_DEReader_destruct(&deReader);
        nitf_Reader_destruct(&reader);
        nitf_Record_destruct(&record);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Read failed ");
        exit(EXIT_FAILURE);
    }

    data[1] = 0;
    fprintf(stdout, "Data after set seek: |%s|\n", data);

    /*
        The last read advanced to position 5 so relative position10 should be
        the last byte in the file
    */

    if (nitf_DEReader_seek(deReader, (nitf_Off) 10, SEEK_CUR, error) == (nitf_Off) - 1)
    {
        NITF_FREE(data);
        nitf_DEReader_destruct(&deReader);
        nitf_Reader_destruct(&reader);
        nitf_Record_destruct(&record);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Read failed ");
        exit(EXIT_FAILURE);
    }

    if (!nitf_DEReader_read(deReader, data, 1, error))
    {
        NITF_FREE(data);
        nitf_DEReader_destruct(&deReader);
        nitf_Reader_destruct(&reader);
        nitf_Record_destruct(&record);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Read failed ");
        exit(EXIT_FAILURE);
    }

    data[1] = 0;
    fprintf(stdout, "Data after current seek: |%s|\n", data);

    if (nitf_DEReader_seek(deReader, (nitf_Off) - 2, SEEK_END, error) == (nitf_Off) - 1)
    {
        NITF_FREE(data);
        nitf_DEReader_destruct(&deReader);
        nitf_Reader_destruct(&reader);
        nitf_Record_destruct(&record);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Read failed ");
        exit(EXIT_FAILURE);
    }

    if (!nitf_DEReader_read(deReader, data, 1, error))
    {
        NITF_FREE(data);
        nitf_DEReader_destruct(&deReader);
        nitf_Reader_destruct(&reader);
        nitf_Record_destruct(&record);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Read failed ");
        exit(EXIT_FAILURE);
    }

    data[1] = 0;
    fprintf(stdout, "Data after end seek: |%s|\n", data);

    /*    Clean-up */

    NITF_FREE(data);
    nitf_DEReader_destruct(&deReader);
    nitf_Reader_destruct(&reader);
    nitf_Record_destruct(&record);
    nitf_IOHandle_close(in);
    return 0;

}
Esempio n. 12
0
int main(int argc, char**argv)
{
    nitf_Error error;
    nitf_PluginRegistry* reg;
    NITF_PLUGIN_TRE_HANDLER_FUNCTION test_main;
    int bad = 0;
    if (argc != 2)
    {
        printf("Usage: %s <TRE>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    reg = nitf_PluginRegistry_getInstance(&error);

    if (!reg)
    {
        nitf_Error_print(&error, stdout, "Exiting...");
        exit(EXIT_FAILURE);
    }
    /*  Don't need this now that it is a singleton
     *
     * if (! nitf_PluginRegistry_load(reg, &error) )
     * {
     *   nitf_Error_print(&error, stdout, "Exiting...");
     *   exit(EXIT_FAILURE);
     * }
     */

    nitf_HashTable_print(reg->treHandlers);

    test_main =
        nitf_PluginRegistry_retrieveTREHandler(reg,
                                               argv[1],
                                               &bad,
                                               &error);


    if (bad)
    {
        nitf_Error_print(&error, stderr, "Error!");
    }
    else if (test_main == (NITF_PLUGIN_TRE_HANDLER_FUNCTION)NULL)
    {
        printf("No such plugin could be found\n");
    }
    else
    {
        int ok;
        printf("Found DLL and main!!!\n");
        ok = (*test_main)(0, NULL, NULL, &error);
        if (!ok)
        {
            nitf_Error_print(&error, stderr , "");
        }

    }


    /*  Don't need this now that the registry is a singleton
     *  if (! nitf_PluginRegistry_unload(reg, &error) )
     *  {
     *    nitf_Error_print(&error, stdout, "Exiting...");
     *    exit(EXIT_FAILURE);
     *  }
     */

    /*  Don't need this now that the registry is a singleton
     *
     *  nitf_PluginRegistry_destruct(&reg);
     */
    return 0;

}
Esempio n. 13
0
int main(int argc, char *argv[])
{
    nitf_FileHeader *fhdr;          /* File header supplying fields */
    nitf_ImageSubheader *subhdr;    /* Subheader supplying fields */
    nitf_Uint32 valueU32Before;     /* Value buffer */
    nitf_Uint32 valueU32After;      /* Value buffer */
    nitf_Uint64 valueU64Before;     /* Value buffer */
    nitf_Uint64 valueU64After;      /* Value buffer */
    char *valueStrBefore;           /* Value buffer */
    /* Value buffer */
    static char valueStrAfter[STR_LEN + 2];
    nitf_Uint32 valueStrLen;        /* Value buffer */
    static nitf_Error errorObj;     /* Error object for messages */
    nitf_Error *error;              /* Pointer to the error object */

    error = &errorObj;

    fhdr = nitf_FileHeader_construct(error);
    if (fhdr == NULL)
    {
        nitf_Error_print(error, stdout, "Error creating image subheader");
        exit(EXIT_FAILURE);
    }

    subhdr = nitf_ImageSubheader_construct(error);
    if (subhdr == NULL)
    {
        nitf_Error_print(error, stdout, "Error creating image subheader");
        exit(EXIT_FAILURE);
    }

    /*    Set some fields (should work) */
    valueU32Before = 12345;
    if (nitf_Field_setUint32(subhdr->NITF_XBANDS, valueU32Before, error))
        fprintf(stdout,
                "Set of XBANDS via nitf_Field_setUint32 worked as expected\n");
    else
        nitf_Error_print(error, stdout,
                         "Unexpected error setting XBANDS via nitf_Field_setUint32");

    nitf_Field_get(subhdr->NITF_XBANDS, (NITF_DATA *) & valueU32After,
                   NITF_CONV_UINT, NITF_INT32_SZ, error);
    fprintf(stdout,
            "Set of XBANDS via nitf_Field_setUint32 original %d readback %d\n",
            valueU32Before, valueU32After);

    valueU32Before = 1234;
    if (nitf_Field_setUint32(subhdr->NITF_COMRAT, valueU32Before, error))
        fprintf(stdout,
                "Set of COMRAT via nitf_Field_setUint32 worked as expected\n");
    else
        nitf_Error_print(error, stdout,
                         "Unexpected error setting COMRAT via nitf_Field_setUint32");

    nitf_Field_get(subhdr->NITF_COMRAT, (NITF_DATA *) & valueU32After,
                   NITF_CONV_UINT, NITF_INT32_SZ, error);
    fprintf(stdout,
            "Set of COMRAT via nitf_Field_setUint32 original %d readback %d\n",
            valueU32Before, valueU32After);

    valueU64Before = 11234567890ll;
    if (nitf_Field_setUint64(fhdr->NITF_FL, valueU64Before, error))
        fprintf(stdout,
                "Set of FL via nitf_Field_setUint64 worked as expected\n");
    else
        nitf_Error_print(error, stdout,
                         "Unexpected error setting FL via nitf_Field_setUint64");

    nitf_Field_get(fhdr->NITF_FL, (NITF_DATA *) & valueU64After,
                   NITF_CONV_UINT, NITF_INT64_SZ, error);
    fprintf(stdout,
            "Set of FL via nitf_Field_setUint64 original %llu readback %llu\n",
            valueU64Before, valueU64After);

    valueStrBefore = "TestStr";
    if (nitf_Field_setString(subhdr->NITF_IID2, valueStrBefore, error))
        fprintf(stdout,
                "Set of IID2 via nitf_Field_setString worked as expected\n");
    else
        nitf_Error_print(error, stdout,
                         "Unexpected error setting IID2 via nitf_Field_setString");

    nitf_Field_get(subhdr->NITF_IID2, (NITF_DATA *) valueStrAfter,
                   NITF_CONV_STRING, STR_LEN, error);
    fprintf(stdout,
            "Set of IID2 via nitf_Field_setString original %s readback %s\n",
            valueStrBefore, valueStrAfter);

    valueStrBefore = "1234";
    if (nitf_Field_setString(subhdr->NITF_NCOLS, valueStrBefore, error))
        fprintf(stdout,
                "Set of NCOLS via nitf_Field_setString worked as expected\n");
    else
        nitf_Error_print(error, stdout,
                         "Unexpected error setting NCOLS via nitf_Field_setString");

    nitf_Field_get(subhdr->NITF_NCOLS, (NITF_DATA *) valueStrAfter,
                   NITF_CONV_STRING, STR_LEN, error);
    fprintf(stdout,
            "Set of NCOLS via nitf_Field_setString original %s readback %s\n",
            valueStrBefore, valueStrAfter);

    /*    Set some fields (should fail) */

    valueU32Before = 123;
    if (nitf_Field_setUint32(fhdr->NITF_FBKGC, valueU32Before, error))
        fprintf(stdout,
                "Set of FBKGC via nitf_Field_setUnit32 worked expected error\n");
    else
        nitf_Error_print(error, stdout,
                         "Expected error setting FBKGC via nitf_Field_setUint32");

    valueStrBefore = "123";
    if (nitf_Field_setString(fhdr->NITF_FBKGC, valueStrBefore, error))
        fprintf(stdout,
                "Set of FBKGC via nitf_Field_setString worked expected error\n");
    else
        nitf_Error_print(error, stdout,
                         "Expected error setting FBKGC via nitf_Field_setString");

    valueStrBefore = "12g";
    if (nitf_Field_setString(subhdr->NITF_NCOLS, valueStrBefore, error))
        fprintf(stdout,
                "Set of NCOLS via nitf_Field_setString worked expected error\n");
    else
        nitf_Error_print(error, stdout,
                         "Expected error setting NCOLS via nitf_Field_setString");

    valueU32Before = 3;
    if (nitf_Field_setUint32(subhdr->NITF_NBANDS, valueU32Before, error))
        fprintf(stdout,
                "Set of NBANDS via nitf_Field_setUint32 worked expected error\n");
    else
        nitf_Error_print(error, stdout,
                         "Expected error setting NBANDS via nitf_Field_setUint32");

    return 0;

}
Esempio n. 14
0
int main(int argc, char *argv[])
{
    FILE *vector;                    /* File stream for input vector */
    /* Arguments for new */
    test_nitf_ImageIOConstructArgs *newArgs;
    /* Arguments for read */
    test_nitf_ImageIOReadArgs *readArgs;
    char *errorStr;                  /* Error string */

    nitf_ImageSubheader *subheader;   /* Subheader for ImageIO constructor */
    nitf_IOHandle io;                /* Handle for output */
    nitf_Error error;                /* Error object */
    nitf_ImageIO *image;             /* ImageIO for image */
    nitf_Uint8 *user[NUM_BANDS_MAX]; /* User buffer for write rows */
    nitf_Uint8 ***data;              /* Generated data [band][row][col] */
    nitf_Uint32 band;                /* Current band */
    nitf_Uint32 row;                 /* Current row */
    nitf_Uint32 col;                 /* Current  column*/

    if (argc < 3)
    {
        fprintf(stderr, "Not enough arguments\n");
        exit(-1);
    }

    vector = fopen(argv[1], "r");
    if (vector == NULL)
    {
        fprintf(stderr, "Error opening vector file %s\n", argv[1]);
        exit(-1);
    }

    newArgs = test_nitf_ImageIOReadConstructArgs(vector, &errorStr);
    if (newArgs == NULL)
    {
        fprintf(stderr, "%s\n", errorStr);
        return(-1);
    }

    fclose(vector);

    /*    Create a fake image subheader to give to ImageIO constructor */

    subheader = test_nitf_ImageIO_fakeSubheader(newArgs, &errorStr);
    if (subheader == NULL)
    {
        fprintf(stderr, "%s", error);
        return(-1);
    }

    /*      Create Image */

    if (strcmp(newArgs->dataPattern, "brcI4") == 0)
    {
        data = (nitf_Uint8 ***) test_nitf_ImageIO_brcI4(newArgs, &errorStr);
        if (data == NULL)
        {
            fprintf(stderr, "%s\n", errorStr);
            exit(-1);
        }
    }
    else if (strcmp(newArgs->dataPattern, "brcC8") == 0)
    {
        data = (nitf_Uint8 ***) test_nitf_ImageIO_brcC8(newArgs, &errorStr);
        if (data == NULL)
        {
            fprintf(stderr, "%s\n", errorStr);
            exit(-1);
        }
    }
    else
    {
        fprintf(stderr, "Invalid pattern method %s\n");
        exit(-1);
    }

    /*      Create output file */

    io = nitf_IOHandle_create(argv[2],
                              NITF_ACCESS_WRITEONLY, NITF_CREATE | NITF_TRUNCATE, &error);
    if (NITF_INVALID_HANDLE(io))
    {
        nitf_Error_print(&error, stderr, "Error creating output file");
        exit(1);
    }

    /* Create the ImageIO structure */

    /*               What about segment length in write ?? */

    image = nitf_ImageIO_construct(subheader, 0, 0, NULL, NULL, &error);
    if (image == NULL)
    {
        nitf_Error_print(&error, stderr, "Error creating ImageIO");
        exit(1);
    }

    /* Setup for write */

    nitf_ImageIO_setPadPixel(image, newArgs->padValue,
                             NITF_NBPP_TO_BYTES(newArgs->nBits));

    if (nitf_ImageIO_writeSequential(image, io, &error) == 0)
    {
        nitf_Error_print(&error, stderr, "Error creating ImageIO");
        exit(1);
    }

    /* Write rows */

    for (row = 0;row < newArgs->nRows;row++)
    {
        for (band = 0;band < newArgs->nBands;band++)
            user[band] = (nitf_Uint8 *) & (data[band][row][0]);
        if (!nitf_ImageIO_writeRows(image, io, 1, user, &error))
        {
            nitf_Error_print(&error, stderr, "Writing rows");
            exit(1);
        }
    }

    if (!nitf_ImageIO_writeDone(image, io, &error))
    {
        nitf_Error_print(&error, stderr, "Writing rows");
        exit(1);
    }

    /* Destroy things */

    test_nitf_ImageIO_freeArray(data);
    nitf_ImageIO_destruct(&image);
    nitf_IOHandle_close(io);
    exit(0);
}
Esempio n. 15
0
NITFAPI(int) nitf_TRECursor_iterate(nitf_TRECursor * tre_cursor,
                                    nitf_Error * error)
{
    nitf_TREDescription *dptr;

    int *stack;                 /* used for in conjuction with the stacks */
    int index;                  /* used for in conjuction with the stacks */

    int loopCount = 0;          /* tells how many times to loop */
    int loop_rtni = 0;          /* used for temp storage */
    int loop_idxi = 0;          /* used for temp storage */

    int numIfs = 0;             /* used to keep track of nested Ifs */
    int numLoops = 0;           /* used to keep track of nested Loops */
    int done = 0;               /* flag used for special cases */

    char idx_str[10][10];       /* used for keeping track of indexes */

    if (!tre_cursor->loop || !tre_cursor->loop_idx
        || !tre_cursor->loop_rtn)
    {
        /* not initialized */
        nitf_Error_init(error, "Unhandled TRE Value data type",
                        NITF_CTXT, NITF_ERR_INVALID_PARAMETER);
        return NITF_FAILURE;
    }

    /* count how many descriptions there are */

	dptr = ((nitf_TREPrivateData*)tre_cursor->tre->priv)->description;

    while (!done)
    {
        done = 1;               /* set the flag */

        /* iterate the index */
        tre_cursor->index++;

        if (tre_cursor->index < tre_cursor->numItems)
        {
            memset(tre_cursor->tag_str, 0, TAG_BUF_LEN);

            tre_cursor->prev_ptr = tre_cursor->desc_ptr;
            tre_cursor->desc_ptr = &dptr[tre_cursor->index];

            /* if already in a loop, prepare the array of values */
            if (tre_cursor->looping)
            {
                stack = tre_cursor->loop_idx->st;
                /* assert, because we only prepare for 10 */
                assert(tre_cursor->looping <= 10);

                for (index = 0; index < tre_cursor->looping; index++)
                {
                    NITF_SNPRINTF(idx_str[index], TAG_BUF_LEN,
                                  "[%d]", stack[index]);
                }
            }

            /* check if it is an actual item now */
            /* ASCII string */
            if ((tre_cursor->desc_ptr->data_type == NITF_BCS_A) ||
                    /* ASCII number */
                    (tre_cursor->desc_ptr->data_type == NITF_BCS_N) ||
                    /* raw bytes */
                    (tre_cursor->desc_ptr->data_type == NITF_BINARY))
            {
                NITF_SNPRINTF(tre_cursor->tag_str, TAG_BUF_LEN, "%s",
                        tre_cursor->desc_ptr->tag);
                /* check if data is part of an array */
                if (tre_cursor->looping)
                {
                    stack = tre_cursor->loop_idx->st;
                    for (index = 0; index < tre_cursor->looping; index++)
                    {
                        char entry[64];
                        NITF_SNPRINTF(entry, 64, "[%d]", stack[index]);
                        strcat(tre_cursor->tag_str, entry);
                    }
                }

                /* check to see if we don't know the length */
                if (tre_cursor->desc_ptr->data_count ==
                        NITF_TRE_CONDITIONAL_LENGTH)
                {
                    /* compute it from the function given */
                    if (tre_cursor->desc_ptr->special)
                    {
                        /* evaluate the special string as a postfix expression */
                        tre_cursor->length =
                            nitf_TRECursor_evaluatePostfix(
                                tre_cursor->tre,
                                idx_str,
                                tre_cursor->looping,
                                tre_cursor->desc_ptr->special,
                                error);

                        if (tre_cursor->length < 0)
                        {
                            /* error! */
                            nitf_Error_print(error, stderr, "TRE expression error:");
                            return NITF_FAILURE;
                        }
                    }
                    else
                    {
                        /* should we return failure here? */
                        /* for now, just set the length to 0, which forces an
                           iteration... */
                        tre_cursor->length = 0;
                    }

                    if (tre_cursor->length == 0)
                    {
                        return nitf_TRECursor_iterate(tre_cursor, error);
                    }
                }
                else
                {
                    /* just set the length that was in the TREDescription */
                    tre_cursor->length = tre_cursor->desc_ptr->data_count;
                }
            }
            /* NITF_LOOP, NITF_IF, etc. */
            else if ((tre_cursor->desc_ptr->data_type >=
                      NITF_LOOP)
                     && (tre_cursor->desc_ptr->data_type < NITF_END))
            {
                done = 0;       /* set the flag */

                /* start of a loop */
                if (tre_cursor->desc_ptr->data_type == NITF_LOOP)
                {
                    loopCount =
                        nitf_TRECursor_evalLoops(tre_cursor->tre,
                                       tre_cursor->desc_ptr, idx_str,
                                       tre_cursor->looping, error);
                    if (loopCount > 0)
                    {
                        tre_cursor->looping++;
                        /* record loopcount in @loop stack */
                        nitf_IntStack_push(tre_cursor->loop, loopCount,
                                           error);
                        /* record i in @loop_rtn stack */
                        nitf_IntStack_push(tre_cursor->loop_rtn,
                                           tre_cursor->index, error);
                        /* record a 0 in @loop_idx stack */
                        nitf_IntStack_push(tre_cursor->loop_idx, 0, error);
                    }
                    else
                    {
                        numLoops = 1;
                        /* skip until we see the matching ENDLOOP */
                        while (numLoops
                                && (++tre_cursor->index <
                                    tre_cursor->numItems))
                        {
                            tre_cursor->desc_ptr =
                                &dptr[tre_cursor->index];
                            if (tre_cursor->desc_ptr->data_type ==
                                    NITF_LOOP)
                                numLoops++;
                            else if (tre_cursor->desc_ptr->data_type ==
                                     NITF_ENDLOOP)
                                numLoops--;
                        }
                    }
                }
                /* end of a loop */
                else if (tre_cursor->desc_ptr->data_type == NITF_ENDLOOP)
                {
                    /* retrieve loopcount from @loop stack */
                    loopCount = nitf_IntStack_pop(tre_cursor->loop, error);
                    /* retrieve loop_rtn from @loop_rtn stack */
                    loop_rtni =
                        nitf_IntStack_pop(tre_cursor->loop_rtn, error);
                    /* retrieve loop_idx from @loop_idx stack */
                    loop_idxi =
                        nitf_IntStack_pop(tre_cursor->loop_idx, error);

                    if (--loopCount > 0)
                    {
                        /* record loopcount in @loop stack */
                        nitf_IntStack_push(tre_cursor->loop, loopCount,
                                           error);
                        /* record i in @loop_rtn stack */
                        nitf_IntStack_push(tre_cursor->loop_rtn, loop_rtni,
                                           error);
                        /* record idx in @loop_idx stack */
                        nitf_IntStack_push(tre_cursor->loop_idx,
                                           ++loop_idxi, error);
                        /* jump to the start of the loop */
                        tre_cursor->index = loop_rtni;
                    }
                    else
                    {
                        --tre_cursor->looping;
                    }
                }
                /* an if clause */
                else if (tre_cursor->desc_ptr->data_type == NITF_IF)
                {
                    if (!nitf_TRECursor_evalIf
                            (tre_cursor->tre,
                             tre_cursor->desc_ptr,
                             idx_str,
                             tre_cursor->looping, error))
                    {
                        numIfs = 1;
                        /* skip until we see the matching ENDIF */
                        while (numIfs
                                && (++tre_cursor->index <
                                    tre_cursor->numItems))
                        {
                            tre_cursor->desc_ptr =
                                &dptr[tre_cursor->index];
                            if (tre_cursor->desc_ptr->data_type == NITF_IF)
                                numIfs++;
                            else if (tre_cursor->desc_ptr->data_type ==
                                     NITF_ENDIF)
                                numIfs--;
                        }
                    }
                }
            }
            else
            {
                nitf_Error_init(error, "Unhandled TRE Value data type",
                                NITF_CTXT, NITF_ERR_INVALID_PARAMETER);
                return NITF_FAILURE;
            }
        }
        else
        {
            /* should return FALSE instead. signifies we are DONE iterating! */
            return NITF_FAILURE;
        }
    }
    return NITF_SUCCESS;
}
Esempio n. 16
0
/*
 *  Take a buffer of memory that we read out of a NITF segment
 *  and write it one of two-ways.
 *
 *  For non RGB 24-bit true-color data, write each band separately.
 *  This demonstrates the typical, non-accelerated, generic read.
 *
 *  For 24-bit true-color, if its band interleaved by pixel (mode 'P')
 *  demonstrate accelerated mode, and read without de-interleaving pixels,
 *  then write it to one big image as is.
 *
 */
void writeImage(nitf_ImageSegment * segment,
                char *imageName,
                nitf_ImageReader * deserializer,
                int imageNumber,
                nitf_Uint32 rowSkipFactor,
                nitf_Uint32 columnSkipFactor,
                NITF_BOOL optz,
                nitf_Error * error)
{

    nitf_Uint32 nBits, nBands, xBands, nRows, nColumns;
    size_t subimageSize;
    nitf_SubWindow *subimage;
    unsigned int i;
    int padded;
    nitf_Uint8 **buffer = NULL;
    nitf_Uint32 band;
    nitf_Uint32 *bandList = NULL;

    nitf_DownSampler *pixelSkip;

    /* TODO, replace these macros! */
    NITF_TRY_GET_UINT32(segment->subheader->numBitsPerPixel, &nBits,
                        error);
    NITF_TRY_GET_UINT32(segment->subheader->numImageBands, &nBands, error);
    NITF_TRY_GET_UINT32(segment->subheader->numMultispectralImageBands,
                        &xBands, error);
    nBands += xBands;
    NITF_TRY_GET_UINT32(segment->subheader->numRows, &nRows, error);
    NITF_TRY_GET_UINT32(segment->subheader->numCols, &nColumns, error);
    subimageSize = (nRows / rowSkipFactor) * (nColumns / columnSkipFactor)
                   * NITF_NBPP_TO_BYTES(nBits);

    printf("Image number: %d\n", imageNumber);
    printf("NBANDS -> %d\n"
           "XBANDS -> %d\n"
           "NROWS -> %d\n"
           "NCOLS -> %d\n"
           "PVTYPE -> %.*s\n"
           "NBPP -> %.*s\n"
           "ABPP -> %.*s\n"
           "PJUST -> %.*s\n"
           "IMODE -> %.*s\n"
           "NBPR -> %.*s\n"
           "NBPC -> %.*s\n"
           "NPPBH -> %.*s\n"
           "NPPBV -> %.*s\n"
           "IC -> %.*s\n"
           "COMRAT -> %.*s\n",
           nBands,
           xBands,
           nRows,
           nColumns,
           (int)segment->subheader->pixelValueType->length,
           segment->subheader->pixelValueType->raw,
           (int)segment->subheader->numBitsPerPixel->length,
           segment->subheader->numBitsPerPixel->raw,
           (int)segment->subheader->actualBitsPerPixel->length,
           segment->subheader->actualBitsPerPixel->raw,
           (int)segment->subheader->pixelJustification->length,
           segment->subheader->pixelJustification->raw,
           (int)segment->subheader->imageMode->length,
           segment->subheader->imageMode->raw,
           (int)segment->subheader->numBlocksPerRow->length,
           segment->subheader->numBlocksPerRow->raw,
           (int)segment->subheader->numBlocksPerCol->length,
           segment->subheader->numBlocksPerCol->raw,
           (int)segment->subheader->numPixelsPerHorizBlock->length,
           segment->subheader->numPixelsPerHorizBlock->raw,
           (int)segment->subheader->numPixelsPerVertBlock->length,
           segment->subheader->numPixelsPerVertBlock->raw,
           (int)segment->subheader->imageCompression->length,
           segment->subheader->imageCompression->raw,
           (int)segment->subheader->compressionRate->length,
           segment->subheader->compressionRate->raw);
    

    if (optz)
    {
	/*
         *  There is an accelerated mode for band-interleaved by pixel data.
         *  In that case, we assume that the user doesnt want the data
         *  de-interleaved into separate band buffers.  To make this work
         *  you have to tell us that you want only one band back,
         *  and you have to provide us a singular buffer that is the
         *  actual number of bands x the pixel size.  Then we will
         *  read the window and not de-interleave.
         *  To demonstrate, for RGB24 images, let's we write out the 1 band
	 *  - this will be MUCH faster
	 */
	if (nBands == 3
            && segment->subheader->imageMode->raw[0] == 'P'
            && strncmp("RGB", segment->subheader->imageRepresentation->raw, 3) == 0
            && NITF_NBPP_TO_BYTES(nBits) == 1
            && (strncmp("NC", segment->subheader->imageCompression->raw, 2)
                || strncmp("NM", segment->subheader->imageCompression->raw, 2)))
	{
            subimageSize *= nBands;
            nBands = 1;
            printf("Using accelerated 3-band RGB mode pix-interleaved image\n");
	}


	if (nBands == 2
            && segment->subheader->NITF_IMODE->raw[0] == 'P'
            && NITF_NBPP_TO_BYTES(nBits) == 4
            && segment->subheader->bandInfo[0]->NITF_ISUBCAT->raw[0] == 'I'
            && (strncmp("NC", segment->subheader->NITF_IC->raw, 2)
                || strncmp("NM", segment->subheader->NITF_IC->raw, 2)))
	{
            subimageSize *= nBands;
            nBands = 1;
            printf("Using accelerated 2-band IQ mode pix-interleaved image\n");
	}
    }
    subimage = nitf_SubWindow_construct(error);
    assert(subimage);

    /* 
     *  You need a buffer for each band (unless this is an 
     *  accelerated IQ complex or RGB read, in which case, you
     *  can set the number of bands to 1, and size your buffer
     *  accordingly to receive band-interleaved by pixel data)
     */
    buffer = (nitf_Uint8 **) NITF_MALLOC(nBands * sizeof(nitf_Uint8*));

    /* An iterator for bands */
    band = 0;

    /* 
     *  This tells us what order to give you bands in.  Normally
     *  you just want it in the order of the banding.  For example,
     *  in a non-accelerated band-interleaved by pixel cases, you might
     *  have a band of magnitude and a band of phase.  If you order the
     *  bandList backwards, the phase buffer comes first in the output
     */
    bandList = (nitf_Uint32 *) NITF_MALLOC(sizeof(nitf_Uint32 *) * nBands);

    /* This example reads all rows and cols starting at 0, 0 */
    subimage->startCol = 0;
    subimage->startRow = 0;

    /* Request rows is the full rows dividied by pixel skip (usually 1) */
    subimage->numRows = nRows / rowSkipFactor;

    /* Request columns is the full columns divided by pixel skip (usually 1) */
    subimage->numCols = nColumns / columnSkipFactor;

    /* Construct our pixel skip downsampler (does nothing if skips are 1) */
    pixelSkip = nitf_PixelSkip_construct(rowSkipFactor, 
                                         columnSkipFactor, 
                                         error);
    if (!pixelSkip)
    {
        nitf_Error_print(error, stderr, "Pixel Skip construction failed");
        goto CATCH_ERROR;
    }
    if (!nitf_SubWindow_setDownSampler(subimage, pixelSkip, error))
    {
        nitf_Error_print(error, stderr, "Set down sampler failed");
        goto CATCH_ERROR;
    }

    for (band = 0; band < nBands; band++)
        bandList[band] = band;
    subimage->bandList = bandList;
    subimage->numBands = nBands;

    assert(buffer);
    for (i = 0; i < nBands; i++)
    {
        buffer[i] = (nitf_Uint8 *) NITF_MALLOC(subimageSize);
        assert(buffer[i]);
    }
    if (!nitf_ImageReader_read
            (deserializer, subimage, buffer, &padded, error))
    {
        nitf_Error_print(error, stderr, "Read failed");
        goto CATCH_ERROR;
    }
    for (i = 0; i < nBands; i++)
    {

        nitf_IOHandle toFile;
        char file[NITF_MAX_PATH];
        int pos;

        /* find end slash */
        for (pos = strlen(imageName) - 1;
                pos && imageName[pos] != '\\' && imageName[pos] != '/';
                pos--);

        pos = pos == 0 ? pos : pos + 1;
        NITF_SNPRINTF(file, NITF_MAX_PATH,
                      "%s_%d__%d_%d_%d_band_%d", &imageName[pos],
                      imageNumber, nRows / rowSkipFactor,
                      nColumns / columnSkipFactor, nBits, i);
        /* remove decimals */
        for (pos = strlen(file) - 1; pos; pos--)
            if (file[pos] == '.')
                file[pos] = '_';
        strcat(file, ".out");
        printf("File: %s\n", file);
        toFile = nitf_IOHandle_create(file, NITF_ACCESS_WRITEONLY,
                                      NITF_CREATE, error);
        if (NITF_INVALID_HANDLE(toFile))
        {
            nitf_Error_print(error, stderr,
                             "IO handle creation failed for raw band");
            goto CATCH_ERROR;
        }
        if (!nitf_IOHandle_write(toFile,
                                 (const char *) buffer[i],
                                 subimageSize, error))
        {
            nitf_Error_print(error, stderr, 
                             "IO handle write failed for raw band");
            goto CATCH_ERROR;
        }
        nitf_IOHandle_close(toFile);
    }

    /* free buffers */
    for (i = 0; i < nBands; i++)
        NITF_FREE(buffer[i]);

    NITF_FREE(buffer);
    NITF_FREE(bandList);
    nitf_SubWindow_destruct(&subimage);
    nitf_DownSampler_destruct(&pixelSkip);

    return;

CATCH_ERROR:
    /* free buffers */
    for (i = 0; i < nBands; i++)
        NITF_FREE(buffer[i]);
    NITF_FREE(buffer);
    NITF_FREE(bandList);
    printf("ERROR processing\n");
}
Esempio n. 17
0
int main(int argc, char **argv)
{

    /*  This is the error we hopefully wont receive  */
    nitf_Error         e;

    /*  This is the reader  */
    nitf_Reader*     reader;

    /*  This is the record of the file we are reading  */
    nitf_Record*       record;


    /*  This is the io handle we will give the reader to parse  */
    nitf_IOHandle      io;


    /*  These iterators are for going through the image segments  */
    nitf_ListIterator  iter;
    nitf_ListIterator  end;

    /*  If you didnt give us a nitf file, we're croaking  */
    if (argc != 2)
    {
        printf("Usage: %s <nitf-file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }


    reader = nitf_Reader_construct(&e);
    if (!reader)
    {
        nitf_Error_print(&e, stderr, "nitf::Reader::construct() failed");
        exit(EXIT_FAILURE);
    }

    /*  If you did, though, we'll be nice and open it for you  */
    io = nitf_IOHandle_create(argv[1],
                              NITF_ACCESS_READONLY,
                              NITF_OPEN_EXISTING,
                              &e);

    /*  But, oh boy, if you gave us a bad location...!  */
    if ( NITF_INVALID_HANDLE( io ) )
    {
        /*  You had this coming!  */
        nitf_Error_print(&e, stderr, "nitf::IOHandle::create() failed");
        exit(EXIT_FAILURE);
    }

    /*  Read the file  */
    record = nitf_Reader_read(reader,
                              io,
                              &e);
    if (!record)
    {
        nitf_Error_print(&e, stderr, "nitf::Reader::read() failed");
        exit(EXIT_FAILURE);
    }

    /*  Set the iterator to traverse the list of image segments  */
    iter = nitf_List_begin(record->images);
    /*  And set this one to the end, so we'll know when we're done!  */
    end  = nitf_List_end(record->images);

    /*  While we are not done...  */
    while ( nitf_ListIterator_notEqualTo(&iter, &end) )
    {

        /*  Get the image segment as its proper object  */
        nitf_ImageSegment* imageSegment =
            (nitf_ImageSegment*)nitf_ListIterator_get(&iter);

        assert( imageSegment->subheader);
        if ( imageSegment->subheader->userDefinedSection )
            findInExtensions( imageSegment->subheader->userDefinedSection );
        else
            printf("Nothing found in user defined section!\n");

        if ( imageSegment->subheader->extendedSection )
            findInExtensions( imageSegment->subheader->extendedSection );
        else
            printf("Nothing found in extended section!\n");


        /*  Increment the iterator so we can continue  */
        nitf_ListIterator_increment(&iter);
    }

    nitf_Record_destruct(&record);
    nitf_Reader_destruct(&reader);
    nitf_IOHandle_close(io);

    return 0;
}
Esempio n. 18
0
void doWrite(nitf_Record * record, char *inRootFile, char *outFile)
{
    nitf_ListIterator iter;

    nitf_ImageWriter *iWriter;
    nitf_ImageSource *iSource;

    nitf_SegmentWriter *segmentWriter;
    nitf_SegmentSource *segmentSource;

    nitf_ListIterator end;
    int i;
    int numImages;
    int numTexts;
    int numDataExtensions;
    nitf_Writer *writer = NULL;
    nitf_Error error;
    nitf_IOHandle output_io = nitf_IOHandle_create(outFile,
                              NITF_ACCESS_WRITEONLY,
                              NITF_CREATE,
                              &error);

    if (NITF_INVALID_HANDLE(output_io))
    {
        goto CATCH_ERROR;
    }

    writer = nitf_Writer_construct(&error);
    if (!writer)
    {
        goto CATCH_ERROR;
    }
    if (!nitf_Writer_prepare(writer, record, output_io, &error))
    {
        goto CATCH_ERROR;
    }

    if (!nitf_Field_get
            (record->header->numImages, &numImages, NITF_CONV_INT,
             NITF_INT32_SZ, &error))
    {
        nitf_Error_print(&error, stderr, "nitf::Value::get() failed");
        numImages = 0;
    }

    if (!nitf_Field_get
            (record->header->numTexts, &numTexts, NITF_CONV_INT,
             NITF_INT32_SZ, &error))
    {
        nitf_Error_print(&error, stderr, "nitf::Value::get() failed");
        numTexts = 0;
    }

    if (!nitf_Field_get
            (record->header->numDataExtensions, &numDataExtensions, NITF_CONV_INT,
             NITF_INT32_SZ, &error))
    {
        nitf_Error_print(&error, stderr, "nitf::Value::get() failed");
        numDataExtensions = 0;
    }

    if (record->images)
    {
        end = nitf_List_end(record->images);
        for (i = 0; i < numImages; i++)
        {
            int nbands;
            nitf_ImageSegment *imseg = NULL;
            iter = nitf_List_at(record->images, i);
            assert(nitf_ListIterator_notEqualTo(&iter, &end));

            imseg = (nitf_ImageSegment *) nitf_ListIterator_get(&iter);
            assert(imseg);

            if (!nitf_Field_get
                    (imseg->subheader->numImageBands, &nbands, NITF_CONV_INT,
                     NITF_INT32_SZ, &error))
                goto CATCH_ERROR;

            iWriter = nitf_Writer_newImageWriter(writer, i, &error);
            if (!iWriter)
            {
                goto CATCH_ERROR;
            }
            iSource = setupBands(nbands, i, inRootFile);
            if (!iSource)
                goto CATCH_ERROR;
            if (!nitf_ImageWriter_attachSource(iWriter, iSource, &error))
                goto CATCH_ERROR;
        }
    }

    if (record->texts)
    {
        end = nitf_List_end(record->texts);
        for (i = 0; i < numTexts; i++)
        {
            nitf_TextSegment *textSeg = NULL;
            char *inFile = NULL;
            nitf_IOHandle sourceHandle;

            iter = nitf_List_at(record->texts, i);
            assert(nitf_ListIterator_notEqualTo(&iter, &end));

            textSeg = (nitf_TextSegment *) nitf_ListIterator_get(&iter);
            assert(textSeg);

            segmentWriter = nitf_Writer_newTextWriter(writer, i, &error);
            if (!segmentWriter)
            {
                goto CATCH_ERROR;
            }

            /* setup file */
            inFile = makeBandName(inRootFile, "text", i, -1);
            sourceHandle =
                nitf_IOHandle_create(inFile, NITF_ACCESS_READONLY,
                                     NITF_OPEN_EXISTING, &error);
            if (NITF_INVALID_HANDLE(sourceHandle))
                goto CATCH_ERROR;

            freeBandName(&inFile);

            segmentSource = nitf_SegmentFileSource_construct(sourceHandle, 0, 0, &error);
            if (!segmentSource)
                goto CATCH_ERROR;
            if (!nitf_SegmentWriter_attachSource(segmentWriter, segmentSource, &error))
                goto CATCH_ERROR;
        }
    }

    if (record->dataExtensions)
    {
        end = nitf_List_end(record->dataExtensions);
        for (i = 0; i < numDataExtensions; i++)
        {
            nitf_DESegment *DESeg = NULL;
            char *inFile = NULL;
            nitf_IOHandle sourceHandle;

            iter = nitf_List_at(record->dataExtensions, i);
            assert(nitf_ListIterator_notEqualTo(&iter, &end));

            DESeg = (nitf_DESegment *) nitf_ListIterator_get(&iter);
            assert(DESeg);

            segmentWriter = nitf_Writer_newDEWriter(writer, i, &error);
            if (!segmentWriter)
            {
                goto CATCH_ERROR;
            }

            /* setup file */
            inFile = makeBandName(inRootFile, "DE", i, -1);
            sourceHandle =
                nitf_IOHandle_create(inFile, NITF_ACCESS_READONLY,
                                     NITF_OPEN_EXISTING, &error);
            if (NITF_INVALID_HANDLE(sourceHandle))
                goto CATCH_ERROR;

            freeBandName(&inFile);

            segmentSource = nitf_SegmentFileSource_construct(sourceHandle, 0, 0, &error);
            if (!segmentSource)
                goto CATCH_ERROR;
            if (!nitf_SegmentWriter_attachSource(segmentWriter, segmentSource, &error))
                goto CATCH_ERROR;

        }
    }

    if (!nitf_Writer_write(writer, &error))
    {
        goto CATCH_ERROR;
    }


    /*nitf_ImageSource_destruct(&iSource);*/
    nitf_IOHandle_close(output_io);
    nitf_Writer_destruct(&writer);
    return;
CATCH_ERROR:
    nitf_Error_print(&error, stderr, "During write");
    exit(EXIT_FAILURE);
}
Esempio n. 19
0
NITF_BOOL writeImage(nitf_ImageSegment* segment, nitf_IOHandle input_io, nitf_IOHandle output_io)
{
    nitf_Error error;
    nitf_Off offset;
    int ret;

    nitf_ImageIO* ioClone;

    nitf_Uint8** buffer;
    nitf_Uint32 nBits, nBands, xBands, nRows, nColumns;
    nitf_SubWindow *subimage;
    size_t subimageSize;
    nitf_Uint32 band;
    nitf_Uint32 *bandList;
    NITF_BOOL success;
    int padded;

    nitf_ImageSource *imgSrc;  /* Image source object */
    nitf_BandSource *bandSrc;   /* Current band source object */


    /* clone the imageIO */
    ioClone = nitf_ImageIO_clone(segment->imageIO, &error);
    if (!ioClone)
    {
        nitf_Error_print(&error, stderr, "Clone failed");
        goto CATCH_ERROR;
    }

    /* get IO offset, and set the offset for the ImageIO */
    offset = nitf_IOHandle_tell(output_io, &error);
    if (!NITF_IO_SUCCESS(offset)) goto CATCH_ERROR;

    if (!nitf_ImageIO_setFileOffset(segment->imageIO, offset, &error))
    {
        goto CATCH_ERROR;
    }

    /*   Read image */

    GET_UINT32(segment->subheader->numBitsPerPixel, &nBits, &error);
    GET_UINT32(segment->subheader->numImageBands, &nBands, &error);
    GET_UINT32(segment->subheader->numMultispectralImageBands, &xBands, &error);
    nBands += xBands;
    GET_UINT32(segment->subheader->numRows, &nRows, &error);
    GET_UINT32(segment->subheader->numCols, &nColumns, &error);
    subimageSize = nRows * nColumns * NITF_NBPP_TO_BYTES(nBits);


    /* Allcoate buffers */
    buffer = (nitf_Uint8 **)malloc(8 * nBands);
    assert(buffer);

    for (band = 0; band < nBands; band++)
    {
        buffer[band] = (nitf_Uint8*)malloc(subimageSize);
        assert(buffer[band]);
    }

    /*  Set-up band array and subimage */

    bandList = (nitf_Uint32 *)malloc(sizeof(nitf_Uint32 *) * nBands);

    subimage = nitf_SubWindow_construct(&error);
    assert(subimage);

    subimage->startCol = 0;
    subimage->startRow = 0;
    subimage->numRows = nRows;
    subimage->numCols = nColumns;

    for (band = 0; band < nBands; band++)
    {
        bandList[band] = band;
    }
    subimage->bandList = bandList;
    subimage->numBands = nBands;

    /*  Read data */

    if (!nitf_ImageIO_read(ioClone,
                           input_io, subimage, buffer, &padded, &error) )
    {
        nitf_Error_print(&error, stderr, "Read failed");
        return(0);
    }
    free(bandList);

    /* Setup for image source */

    imgSrc = nitf_ImageSource_construct(&error);
    if (imgSrc == NULL)
        return(0);
    for (band = 0; band < nBands; band++)
    {
        bandSrc = nitf_MemorySource_construct(buffer[band], (size_t) subimageSize,
                                              (nitf_Off) 0, NITF_NBPP_TO_BYTES(nBits), 0, &error);
        if (bandSrc == NULL)
            return(0);

        if (!nitf_ImageSource_addBand(imgSrc, bandSrc, &error))
            return(0);
    }

    /* Do write */

    ret = doWrite(segment, imgSrc, output_io, ioClone);

    if (ioClone) nitf_ImageIO_destruct(&ioClone);
    nitf_ImageSource_destruct(&imgSrc);

    /* OK return */
    return ret;

CATCH_ERROR:
    if (ioClone) nitf_ImageIO_destruct(&ioClone);
    printf("ERROR processing\n");
    return 0;
}
Esempio n. 20
0
void manuallyWriteImageBands(nitf_ImageSegment * segment,
                             const char *imageName,
                             nitf_ImageReader * deserializer,
                             int imageNumber, nitf_Error * error)
{
    char *file;
    nitf_Uint32 nBits, nBands, xBands, nRows, nColumns;
    size_t subimageSize;
    nitf_SubWindow *subimage;
    unsigned int i;
    int padded;
    nitf_Uint8 **buffer = NULL;
    nitf_Uint32 band;
    nitf_Uint32 *bandList = NULL;

    NITF_TRY_GET_UINT32(segment->subheader->numBitsPerPixel, &nBits,
                        error);
    NITF_TRY_GET_UINT32(segment->subheader->numImageBands, &nBands, error);
    NITF_TRY_GET_UINT32(segment->subheader->numMultispectralImageBands,
                        &xBands, error);
    nBands += xBands;
    NITF_TRY_GET_UINT32(segment->subheader->numRows, &nRows, error);
    NITF_TRY_GET_UINT32(segment->subheader->numCols, &nColumns, error);
    subimageSize = nRows * nColumns * NITF_NBPP_TO_BYTES(nBits);

    printf("Image number: %d\n", imageNumber);
    printf("NBANDS -> %d\n"
           "XBANDS -> %d\n"
           "NROWS -> %d\n"
           "NCOLS -> %d\n"
           "PVTYPE -> %.*s\n"
           "NBPP -> %.*s\n"
           "ABPP -> %.*s\n"
           "PJUST -> %.*s\n"
           "IMODE -> %.*s\n"
           "NBPR -> %.*s\n"
           "NBPC -> %.*s\n"
           "NPPBH -> %.*s\n"
           "NPPBV -> %.*s\n"
           "IC -> %.*s\n"
           "COMRAT -> %.*s\n",
           nBands,
           xBands,
           nRows,
           nColumns,
           (int)segment->subheader->pixelValueType->length,
           segment->subheader->pixelValueType->raw,
           (int)segment->subheader->numBitsPerPixel->length,
           segment->subheader->numBitsPerPixel->raw,
           (int)segment->subheader->actualBitsPerPixel->length,
           segment->subheader->actualBitsPerPixel->raw,
           (int)segment->subheader->pixelJustification->length,
           segment->subheader->pixelJustification->raw,
           (int)segment->subheader->imageMode->length,
           segment->subheader->imageMode->raw,
           (int)segment->subheader->numBlocksPerRow->length,
           segment->subheader->numBlocksPerRow->raw,
           (int)segment->subheader->numBlocksPerCol->length,
           segment->subheader->numBlocksPerCol->raw,
           (int)segment->subheader->numPixelsPerHorizBlock->length,
           segment->subheader->numPixelsPerHorizBlock->raw,
           (int)segment->subheader->numPixelsPerVertBlock->length,
           segment->subheader->numPixelsPerVertBlock->raw,
           (int)segment->subheader->imageCompression->length,
           segment->subheader->imageCompression->raw,
           (int)segment->subheader->compressionRate->length,
           segment->subheader->compressionRate->raw);


    buffer = (nitf_Uint8 **) malloc(sizeof(nitf_Uint8*) * nBands);
    band = 0;
    bandList = (nitf_Uint32 *) malloc(sizeof(nitf_Uint32 *) * nBands);

    subimage = nitf_SubWindow_construct(error);
    assert(subimage);

    subimage->startCol = 0;
    subimage->startRow = 0;
    subimage->numRows = nRows;
    subimage->numCols = nColumns;

    for (band = 0; band < nBands; band++)
        bandList[band] = band;
    subimage->bandList = bandList;
    subimage->numBands = nBands;

    assert(buffer);
    for (i = 0; i < nBands; i++)
    {
        buffer[i] = (nitf_Uint8 *) malloc(subimageSize);
        assert(buffer[i]);
    }
    /*  This should change to returning failures!  */
    /*
       if (! nitf_ImageIO_read(segment->imageIO, io, &subimage, buffer, &padded,
       error) )
       {
       nitf_Error_print(error, stderr, "Read failed");
       goto CATCH_ERROR;
       }
     */
    if (!nitf_ImageReader_read
            (deserializer, subimage, buffer, &padded, error))
    {
        nitf_Error_print(error, stderr, "Read failed");
        goto CATCH_ERROR;
    }
    for (i = 0; i < nBands; i++)
    {

        nitf_IOHandle toFile;
        file = makeBandName(imageName, "img", imageNumber, i);
        toFile = nitf_IOHandle_create(file, NITF_ACCESS_WRITEONLY,
                                      NITF_CREATE, error);
        freeBandName(&file);
        if (NITF_INVALID_HANDLE(toFile))
        {
            goto CATCH_ERROR;

        }
        if (!nitf_IOHandle_write(toFile,
                                 (const char *) buffer[i],
                                 subimageSize, error))

        {
            goto CATCH_ERROR;
        }
        nitf_IOHandle_close(toFile);
    }

    /* free buffers */
    for (i = 0; i < nBands; i++)
    {
        free(buffer[i]);
    }
    free(buffer);
    free(bandList);
    nitf_SubWindow_destruct(&subimage);
    return;

CATCH_ERROR:
    /* free buffers */
    for (i = 0; i < nBands; i++)
    {
        free(buffer[i]);
    }
    free(buffer);
    free(bandList);
    nitf_Error_print(error, stderr, "Manual write failed");


}
Esempio n. 21
0
int main(int argc, char *argv[])
{
    nitf_ImageIO *nitf;                     /* The parent nitf_ImageIO object */
    char errorBuf[NITF_MAX_EMESSAGE];       /* Error buffer */
    nitf_Uint8 **user;                      /* User buffer list */
    int padded;                             /* Pad pixel present flag */
    nitf_IOHandle fileHandle;               /* I/O handle for reads */
    int ofd;                                /* File descriptor for writes */
    FILE *vector;                           /* FILE for reading vectors */
    test_nitf_ImageIOConstructArgs *newArgs;/* Arguments for new */
    test_nitf_ImageIOReadArgs *readArgs;    /* Arguments for read */
    nitf_ImageSubheader *subheader;         /* For constructor */
    size_t subWindowSize;                   /* Sub-window pixel count */
    nitf_SubWindow *subWindow;              /* Argument for read */
    nitf_DownSampler* downSampler;          /* Down-sample object */
    char *error;                            /* Error message return */
    nitf_Error errorObjActual;              /* Error object instance */
    nitf_Error *errorObj;                   /* Error object (pointer) */
    int i;

    errorObj = &errorObjActual;

    /*    Usage */

    if (argc < 2)
    {
        fprintf(stderr,
                "Usage: %s imageVector readVector band0Out band1Out ... >result\n", argv[0]);
        exit(0);
    }

    /*      Read image and read parameters from first and second arguments */

    vector = fopen(argv[1], "r");
    if (vector == NULL)
    {
        fprintf(stderr, "Error opening image vector file %s\n", argv[0]);
        exit(-1);
    }

    newArgs = test_nitf_ImageIOReadConstructArgs(vector, &error);
    if (newArgs == NULL)
    {
        fprintf(stderr, "%s\n", error);
        exit(-1);
    }
    fclose(vector);

    vector = fopen(argv[2], "r");
    if (vector == NULL)
    {
        fprintf(stderr, "Error opening read vector file %s\n", argv[0]);
        exit(-1);
    }

    readArgs = test_nitf_ImageIOReadReadArgs(vector, &error);
    if (readArgs == NULL)
    {
        fprintf(stderr, "%s\n", error);
        exit(-1);
    }
    fclose(vector);

    /*      Allocate user buffers */

    subWindowSize = (readArgs->nRows) * (readArgs->nColumns) * (newArgs->nBits / 8);

    user = (nitf_Uint8 **) malloc(sizeof(nitf_Uint8 *) * (readArgs->nBands));
    if (user == NULL)
    {
        fprintf(stderr, "Error allocating user buffer\n");
        exit(-1);
    }

    for (i = 0;i < readArgs->nBands;i++)
    {
        user[i] = (nitf_Uint8 *) malloc(subWindowSize);
        if (user[i] == NULL)
        {
            fprintf(stderr, "Error allocating user buffer\n");
            exit(-1);
        }
    }

    /*    Create a fake image subheader to give to ImageIO constructor */

    subheader = test_nitf_ImageIO_fakeSubheader(newArgs, &error);
    if (subheader == NULL)
    {
        fprintf(stderr, "%s", error);
        exit(-1);
    }

    /*     Create the ImageIO */

    nitf = nitf_ImageIO_construct(subheader, newArgs->offset,
                                  0,/*length, must be correct for decompression */
                                  NULL, NULL, errorObj);
    if (nitf == NULL)
    {
        fprintf(stderr, "NtfBlk new failed: %s\n", errorBuf);
        fprintf(stderr, "Err: %s\n", errorObj->message);
        exit(0);
    }

    nitf_ImageIO_setPadPixel(nitf, newArgs->padValue,
                             NITF_NBPP_TO_BYTES(newArgs->nBits));

    nitf_ImageIO_print(nitf, stdout);

    /*     Open input file */

    fileHandle = nitf_IOHandle_create(readArgs->name,
                                      NITF_ACCESS_READONLY, 0, errorObj);
    if (NITF_INVALID_HANDLE(fileHandle))
    {
        nitf_Error_init(errorObj, "File open failed",
                        NITF_CTXT, NITF_ERR_OPENING_FILE);
        nitf_Error_print(errorObj, stderr, "File open failed");
        exit(0);
    }

    /*    Setup for read (create and initialize sub-window object */

    if ((subWindow = nitf_SubWindow_construct(errorObj)) == NULL)
    {
        nitf_Error_init(errorObj, "Sub-window object construct failed",
                        NITF_CTXT, NITF_ERR_INVALID_OBJECT);
        nitf_Error_print(errorObj, stderr, "Sub-window object construct failed");
        nitf_IOHandle_close(fileHandle);
        nitf_ImageIO_destruct(&nitf);
        exit(0);
    }

    subWindow->startRow = readArgs->row;
    subWindow->numRows = readArgs->nRows;
    subWindow->startCol = readArgs->column;
    subWindow->numCols = readArgs->nColumns;
    subWindow->bandList = readArgs->bands;
    subWindow->numBands = readArgs->nBands;

    if ((readArgs->rowSkip != 1) || (readArgs->columnSkip != 1))
    {
        if (strcmp(readArgs->downSample, "pixelSkip") == 0)
        {
            if ((downSampler = nitf_PixelSkip_construct(
                                   readArgs->rowSkip, readArgs->columnSkip, errorObj)) == NULL)
            {
                nitf_Error_init(errorObj, "Down-sampler object construct failed",
                                NITF_CTXT, NITF_ERR_INVALID_OBJECT);
                nitf_Error_print(errorObj, stderr,
                                 "Down-sampler object construct failed");
                nitf_IOHandle_close(fileHandle);
                nitf_ImageIO_destruct(&nitf);
                nitf_SubWindow_destruct(&subWindow);
                exit(0);
            }

            if (nitf_SubWindow_setDownSampler(
                        subWindow, downSampler, errorObj) == NITF_FAILURE)
            {
                nitf_Error_init(errorObj, "Read failed",
                                NITF_CTXT, NITF_ERR_READING_FROM_FILE);
                nitf_Error_print(errorObj, stderr, "Read failed");
                nitf_IOHandle_close(fileHandle);
                nitf_ImageIO_destruct(&nitf);
                nitf_SubWindow_destruct(&subWindow);
                nitf_DownSampler_destruct(&downSampler);
                exit(0);
            }
        }
        else if (strcmp(readArgs->downSample, "max") == 0)
        {

            if ((downSampler = nitf_MaxDownSample_construct(
                                   readArgs->rowSkip, readArgs->columnSkip, errorObj)) == NULL)
            {
                nitf_Error_init(errorObj, "Down-sampler object construct failed",
                                NITF_CTXT, NITF_ERR_INVALID_OBJECT);
                nitf_Error_print(errorObj, stderr,
                                 "Down-sampler object construct failed");
                nitf_IOHandle_close(fileHandle);
                nitf_ImageIO_destruct(&nitf);
                nitf_SubWindow_destruct(&subWindow);
                exit(0);
            }

            if (nitf_SubWindow_setDownSampler(
                        subWindow, downSampler, errorObj) == NITF_FAILURE)
            {
                nitf_Error_init(errorObj, "Read failed",
                                NITF_CTXT, NITF_ERR_READING_FROM_FILE);
                nitf_Error_print(errorObj, stderr, "Read failed");
                nitf_IOHandle_close(fileHandle);
                nitf_ImageIO_destruct(&nitf);
                nitf_SubWindow_destruct(&subWindow);
                nitf_DownSampler_destruct(&downSampler);
                exit(0);
            }
        }
        else if (strcmp(readArgs->downSample, "sumSq2") == 0)
        {

            if ((downSampler = nitf_SumSq2DownSample_construct(
                                   readArgs->rowSkip, readArgs->columnSkip, errorObj)) == NULL)
            {
                nitf_Error_init(errorObj, "Down-sampler object construct failed",
                                NITF_CTXT, NITF_ERR_INVALID_OBJECT);
                nitf_Error_print(errorObj, stderr,
                                 "Down-sampler object construct failed");
                nitf_IOHandle_close(fileHandle);
                nitf_ImageIO_destruct(&nitf);
                nitf_SubWindow_destruct(&subWindow);
                exit(0);
            }

            if (nitf_SubWindow_setDownSampler(
                        subWindow, downSampler, errorObj) == NITF_FAILURE)
            {
                nitf_Error_init(errorObj, "Read failed",
                                NITF_CTXT, NITF_ERR_READING_FROM_FILE);
                nitf_Error_print(errorObj, stderr, "Read failed");
                nitf_IOHandle_close(fileHandle);
                nitf_ImageIO_destruct(&nitf);
                nitf_SubWindow_destruct(&subWindow);
                nitf_DownSampler_destruct(&downSampler);
                exit(0);
            }
        }
        else if (strcmp(readArgs->downSample, "select2") == 0)
        {

            if ((downSampler = nitf_Select2DownSample_construct(
                                   readArgs->rowSkip, readArgs->columnSkip, errorObj)) == NULL)
            {
                nitf_Error_init(errorObj, "Down-sampler object construct failed",
                                NITF_CTXT, NITF_ERR_INVALID_OBJECT);
                nitf_Error_print(errorObj, stderr,
                                 "Down-sampler object construct failed");
                nitf_IOHandle_close(fileHandle);
                nitf_ImageIO_destruct(&nitf);
                nitf_SubWindow_destruct(&subWindow);
                exit(0);
            }

            if (nitf_SubWindow_setDownSampler(
                        subWindow, downSampler, errorObj) == NITF_FAILURE)
            {
                nitf_Error_init(errorObj, "Read failed",
                                NITF_CTXT, NITF_ERR_READING_FROM_FILE);
                nitf_Error_print(errorObj, stderr, "Read failed");
                nitf_IOHandle_close(fileHandle);
                nitf_ImageIO_destruct(&nitf);
                nitf_SubWindow_destruct(&subWindow);
                nitf_DownSampler_destruct(&downSampler);
                exit(0);
            }
        }
        else
        {
            nitf_Error_init(errorObj, "Invalid down-sample method",
                            NITF_CTXT, NITF_ERR_INVALID_PARAMETER);
            nitf_Error_fprintf(errorObj, stderr,
                               "Invalid down-sample method: %s\n", readArgs->downSample);
            nitf_IOHandle_close(fileHandle);
            nitf_ImageIO_destruct(&nitf);
            nitf_SubWindow_destruct(&subWindow);
            exit(0);
        }
    }

    /*     Read sub-window */

    if (!nitf_ImageIO_read(nitf, fileHandle, subWindow, user, &padded, errorObj))
    {
        nitf_Error_print(errorObj, stderr, "Read failed");
        nitf_IOHandle_close(fileHandle);
        nitf_ImageIO_destruct(&nitf);
        nitf_SubWindow_destruct(&subWindow);
        exit(0);
    }
    nitf_SubWindow_destruct(&subWindow);

    nitf_IOHandle_close(fileHandle);

    printf("Padded = %d\n", padded);

    /*      Write result */

    for (i = 0;i < readArgs->nBands;i++)
    {
        if ((ofd = open(argv[3+i], O_WRONLY | O_CREAT | O_TRUNC, 0666)) == -1)
        {
            fprintf(stderr, "Output file %d open failed\n", i);
            exit(0);
        }

        write(ofd, user[i], subWindowSize);
        close(ofd);
    }

    return 0;
}
Esempio n. 22
0
nitf_Record *doRead(const char *inFile)
{
    /*  This is the error we hopefully wont receive  */
    nitf_Error e;

    /*  This is the reader  */
    nitf_Reader *reader;

    /*  This is the record of the file we are reading  */
    nitf_Record *record;

    /*  This is the io handle we will give the reader to parse  */
    nitf_IOHandle io;

    int count = 0;
    int numImages;
    int numTexts;
    int numDataExtensions;

    nitf_ListIterator iter;
    nitf_ListIterator end;


    nitf_ImageSegment *imageSegment = NULL;
    nitf_ImageReader *deserializer = NULL;
    nitf_TextSegment *textSegment = NULL;
    nitf_DESegment *deSegment = NULL;
    nitf_SegmentReader *segmentReader = NULL;
    nitf_SegmentReader *deReader = NULL;

    reader = nitf_Reader_construct(&e);
    if (!reader)
    {
        nitf_Error_print(&e, stderr, "nitf::Reader::construct() failed");
        exit(EXIT_FAILURE);
    }

    /*  If you did, though, we'll be nice and open it for you  */
    io = nitf_IOHandle_create(inFile,
                              NITF_ACCESS_READONLY,
                              NITF_OPEN_EXISTING, &e);

    /*  But, oh boy, if you gave us a bad location...!  */
    if (NITF_INVALID_HANDLE(io))
    {
        /*  You had this coming!  */
        nitf_Error_print(&e, stderr, "nitf::IOHandle::create() failed");
        exit(EXIT_FAILURE);
    }

    /*  Read the file  */
    record = nitf_Reader_read(reader, io, &e);
    if (!record)
    {
        nitf_Error_print(&e, stderr, "nitf::Reader::read() failed");
        exit(EXIT_FAILURE);
    }

    if (!nitf_Field_get
            (record->header->numImages, &numImages, NITF_CONV_INT,
             NITF_INT32_SZ, &e))
    {
        nitf_Error_print(&e, stderr, "nitf::Field::get() failed");
        numImages = 0;
    }

    if (!nitf_Field_get
            (record->header->numTexts, &numTexts, NITF_CONV_INT,
             NITF_INT32_SZ, &e))
    {
        nitf_Error_print(&e, stderr, "nitf::Field::get() failed");
        numTexts = 0;
    }

    if (!nitf_Field_get
            (record->header->numDataExtensions, &numDataExtensions, NITF_CONV_INT,
             NITF_INT32_SZ, &e))
    {
        nitf_Error_print(&e, stderr, "nitf::Field::get() failed");
        numDataExtensions = 0;
    }

    if (record->images)
    {
        end = nitf_List_end(record->images);

        for (count = 0; count < numImages; ++count)
        {
            iter = nitf_List_at(record->images, count);
            if (nitf_ListIterator_equals(&iter, &end))
            {
                printf("Out of bounds on iterator [%d]!\n", count);
                exit(EXIT_FAILURE);
            }
            imageSegment = (nitf_ImageSegment *) nitf_ListIterator_get(&iter);
            deserializer = nitf_Reader_newImageReader(reader, count, &e);
            if (!deserializer)
            {
                nitf_Error_print(&e, stderr, "Couldnt spawn deserializer");
                exit(EXIT_FAILURE);
            }
            printf("Writing image %d... ", count);
            /*  Write the thing out  */
            manuallyWriteImageBands(imageSegment, inFile, deserializer, count,
                                    &e);

            nitf_ImageReader_destruct(&deserializer);

            printf("done.\n");
            /*  Increment the iterator so we can continue  */
            nitf_ListIterator_increment(&iter);
        }
    }


    /* loop over texts and read the data to a file */
    if (record->texts)
    {
        end = nitf_List_end(record->texts);

        for (count = 0; count < numTexts; ++count)
        {
            iter = nitf_List_at(record->texts, count);
            if (nitf_ListIterator_equals(&iter, &end))
            {
                printf("Out of bounds on iterator [%d]!\n", count);
                exit(EXIT_FAILURE);
            }
            textSegment = (nitf_TextSegment *) nitf_ListIterator_get(&iter);
            segmentReader = nitf_Reader_newTextReader(reader, count, &e);
            if (!segmentReader)
            {
                nitf_Error_print(&e, stderr, "Couldnt spawn deserializer");
                exit(EXIT_FAILURE);
            }
            printf("Writing text %d... ", count);
            /*  Write the thing out  */
            writeTextData(textSegment, inFile, segmentReader, count, &e);
            nitf_SegmentReader_destruct(&segmentReader);

            /*  Increment the iterator so we can continue  */
            nitf_ListIterator_increment(&iter);
        }
    }

    /*XXX*/
    /* loop over data extensions and read the data to a file */
    if (record->dataExtensions)
    {
        fprintf(stderr, "XXX Data Ext %d\n", numDataExtensions);
        end = nitf_List_end(record->dataExtensions);

        for (count = 0; count < numDataExtensions;  ++count)
        {
            iter = nitf_List_at(record->dataExtensions, count);
            if (nitf_ListIterator_equals(&iter, &end))
            {
                printf("Out of bounds on iterator [%d]!\n", count);
                exit(EXIT_FAILURE);
            }
            deSegment = (nitf_DESegment *) nitf_ListIterator_get(&iter);
            deReader = nitf_Reader_newDEReader(reader, count, &e);
            if (!deReader)
            {
                nitf_Error_print(&e, stderr, "Couldnt spawn deserializer");
                exit(EXIT_FAILURE);
            }
            printf("Writing data extension %d... ", count);
            /*  Write the thing out  */
            writeDEData(deSegment, inFile, deReader, count, &e);
            nitf_SegmentReader_destruct(&segmentReader);

            /*  Increment the iterator so we can continue  */
            nitf_ListIterator_increment(&iter);
        }
    }
    nitf_Reader_destruct(&reader);
    return record;

}
Esempio n. 23
0
int main(int argc, char **argv)
{
    /*  Get the error object       */
    nitf_Error error;

    /* so I can remember what Im doing with args */
    const char* treName;
    const char* fieldName;

    /*  This is the reader object  */
    nitf_Reader *reader;
    nitf_Record *record;
	
    /*  The IO handle  */
    nitf_IOHandle io;
    int num;

    /*  Check argv and make sure we are happy  */
    if (argc != 4)
    {
        printf("Usage: %s <nitf-file> <TRE> <field>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if (nitf_Reader_getNITFVersion(argv[1]) == NITF_VER_UNKNOWN)
    {
	printf("File: %s is not a NITF\n", argv[1]);
	exit(EXIT_FAILURE);
    }
	
    treName = argv[2];
    fieldName = argv[3];

    io = nitf_IOHandle_create(argv[1], NITF_ACCESS_READONLY,
                              NITF_OPEN_EXISTING, &error);

    if (NITF_INVALID_HANDLE(io))
    {
        nitf_Error_print(&error, stdout, "Exiting...");
        exit(EXIT_FAILURE);
    }

    reader = nitf_Reader_construct(&error);
    if (!reader)
    {
        nitf_Error_print(&error, stdout, "Exiting (1) ...");
        exit(EXIT_FAILURE);
    }
   
#if NITF_VERBOSE_READER
    printf("Here are the loaded handlers\n");
    printf("* * * * * * * * * * * * * * * *\n");
    nitf_HashTable_print(reader->reg->treHandlers);
    printf("* * * * * * * * * * * * * * * *\n");
#endif
    record = nitf_Reader_read(reader, io, &error);


    lookForTREField(record->header->extendedSection, treName, fieldName);
    lookForTREField(record->header->userDefinedSection, treName, fieldName);



    if (!nitf_Field_get(record->header->numImages,
                        &num, NITF_CONV_INT, NITF_INT32_SZ, &error))
        goto CATCH_ERROR;

    /* And now show the image information */
    if (num > 0)
    {

        /*  Walk each image and show  */
        nitf_ListIterator iter = nitf_List_begin(record->images);
        nitf_ListIterator end = nitf_List_end(record->images);

        while (nitf_ListIterator_notEqualTo(&iter, &end))
        {
            nitf_ImageSegment *segment =
                (nitf_ImageSegment *) nitf_ListIterator_get(&iter);

	    lookForTREField(segment->subheader->extendedSection, treName, fieldName);
	    lookForTREField(segment->subheader->userDefinedSection, treName, fieldName);
            nitf_ListIterator_increment(&iter);
        }
    }
    else
    {
        printf("No image in file!\n");
    }

    nitf_IOHandle_close(io);
    nitf_Record_destruct(&record);

    nitf_Reader_destruct(&reader);

    return 0;

CATCH_ERROR:
    printf("!!! we had a problem reading the file !!!\n");
    nitf_Error_print(&error, stdout, "Exiting...");
    exit(EXIT_FAILURE);
}
Esempio n. 24
0
int main(int argc, char **argv)
{
    /*  Get the error object       */
    nitf_Error     error;

    /*  This is the reader object  */
    nitf_Reader* reader;
    nitf_Record* record;

    /*  The IO handle  */
    nitf_IOHandle io;
    int num;

    /*  Check argv and make sure we are happy  */
    if ( argc != 2 )
    {
        printf("Usage: %s <nitf-file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    io = nitf_IOHandle_create(argv[1], NITF_ACCESS_READONLY, NITF_OPEN_EXISTING, &error);
    if ( NITF_INVALID_HANDLE( io ) )
    {
        nitf_Error_print(&error, stdout, "Exiting...");
        exit( EXIT_FAILURE );
    }

    reader = nitf_Reader_construct(&error);
    if (!reader)
    {
        nitf_Error_print(&error, stdout, "Exiting (1) ...");
        exit( EXIT_FAILURE );
    }

    /*    record = nitf_Record_construct(&error);
    if (!record)
    {
    nitf_Error_print(&error, stdout, "Exiting (2) ...");
    nitf_Reader_destruct(&reader);
    exit( EXIT_FAILURE );
    }*/


#if NITF_VERBOSE_READER
    printf("Here are the loaded handlers\n");
    printf("* * * * * * * * * * * * * * * *\n");
    nitf_HashTable_print(reader->reg->treHandlers);
    printf("* * * * * * * * * * * * * * * *\n");
#endif

    if ( ! (record = nitf_Reader_read(reader, io, &error  )) )
    {
        nitf_Error_print(&error, stdout, "Exiting ...");
        exit(EXIT_FAILURE);
    }

    printf("User defined: in file header\n");
    showExtSection(record->header->userDefinedSection);
    printf("Extended defined: in file header\n");
    showExtSection(record->header->extendedSection);



    if (!nitf_Field_get(record->header->numImages,
                        &num,
                        NITF_CONV_INT,
                        NITF_INT32_SZ,
                        &error))
        nitf_Error_print(&error, stdout, "Skipping b/c Invalid numImages");
    /* And now show the image information */
    else if (num > 0)
    {

        /*  Walk each image and show  */
        nitf_ListIterator iter = nitf_List_begin(record->images);
        nitf_ListIterator end  = nitf_List_end(record->images);

        while ( nitf_ListIterator_notEqualTo(&iter, &end) )
        {
            nitf_ImageSegment* segment =
                (nitf_ImageSegment*)nitf_ListIterator_get(&iter);

            printf("User defined: in image segment\n");
            showExtSection(segment->subheader->userDefinedSection);
            printf("Extended defined: in image segment\n");
            showExtSection(segment->subheader->extendedSection);


            nitf_ListIterator_increment(&iter);

        }
    }
    else
    {
        printf("No image in file!\n");
    }




    nitf_IOHandle_close(io);
    nitf_Record_destruct(&record);

    if ( !nitf_List_isEmpty(reader->warningList))
    {
        /*  Iterator to a list  */
        nitf_ListIterator it;

        /*  Iterator to the end of list  */
        nitf_ListIterator endList;

        it      = nitf_List_begin(reader->warningList);

        /*  End of list pointer  */
        endList = nitf_List_end(reader->warningList);

        printf("WARNINGS: ");
        printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");

        /*  While we are not at the end  */
        while ( nitf_ListIterator_notEqualTo( &it, &endList ) )
        {
            /*  Get the last data  */
            char* p = (char*)nitf_ListIterator_get(&it);
            /*  Make sure  */
            assert(p != NULL);

            /*  Show the data  */
            printf("\tFound problem: [%s]\n\n", p);

            /*  Increment the list iterator  */
            nitf_ListIterator_increment(&it);
        }
        printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
    }

    nitf_Reader_destruct(&reader);

    return 0;
}
Esempio n. 25
0
void setupImageSubheader(
    test_nitf_ImageIOConstructArgs *args,
    nitf_Record *record, nitf_ImageSegment *seg)
{
    nitf_ImageSubheader *subheader;   /* Subheader from segment */
    nitf_Uint32 nBands;               /* Number of bands */
    nitf_BandInfo **bands;            /* BandInfo array */
    nitf_Error errorObj;              /* Error object argument */
    nitf_Uint32 i;

    subheader = seg->subheader;
    nitf_Field_setUint32(subheader->numRows, args->nRows, &errorObj);
    nitf_Field_setUint32(subheader->numCols, args->nColumns, &errorObj);
    nitf_Field_setUint32(subheader->numImageBands, args->nBands, &errorObj);
    nitf_Field_setUint32(subheader->numMultispectralImageBands,
                         args->nMultiBands, &errorObj);
    nitf_Field_setUint32(subheader->numBlocksPerRow,
                         args->nBlksPerRow, &errorObj);
    nitf_Field_setUint32(subheader->numBlocksPerCol,
                         args->nBlksPerColumn, &errorObj);
    nitf_Field_setUint32(subheader->numPixelsPerVertBlock,
                         args->nRowsPerBlk, &errorObj);
    nitf_Field_setUint32(subheader->numPixelsPerHorizBlock,
                         args->nColumnsPerBlk, &errorObj);
    nitf_Field_setString(subheader->imageMode, args->mode, &errorObj);
    nitf_Field_setString(subheader->imageCompression,
                         args->compression, &errorObj);
    nBands = args->nBands;
    if (nBands == 0)
        nBands = args->nMultiBands;

    bands = (nitf_BandInfo **) NITF_MALLOC(sizeof(nitf_BandInfo *));
    if (bands == NULL)
    {
        nitf_Error_init(&errorObj, NITF_STRERROR(NITF_ERRNO),
                        NITF_CTXT, NITF_ERR_MEMORY);
        nitf_Error_print(&errorObj, stderr, "Error setting up band source ");
        exit(EXIT_FAILURE);
    }

    for (i = 0;i < nBands;i++)
    {
        bands[i] = nitf_BandInfo_construct(&errorObj);
        if (bands[i] == NULL)
        {
            nitf_Error_print(&errorObj, stderr, "Error setting up band source ");
            exit(EXIT_FAILURE);
        }

        if (!nitf_BandInfo_init(bands[i],
                                "M",      /* The band representation, Nth band */
                                " ",      /* The band subcategory */
                                "N",      /* The band filter condition */
                                "   ",    /* The band standard image filter code */
                                0,        /* The number of look-up tables */
                                0,        /* The number of entries/LUT */
                                NULL,     /* The look-up tables */
                                &errorObj))
        {
            nitf_Error_print(&errorObj, stderr, "Error setting up band source ");
            exit(EXIT_FAILURE);
        }
    }

    if (!nitf_ImageSubheader_setPixelInformation(subheader,
            args->pixelType,      /* Pixel value type */
            args->nBits,          /* Number of bits/pixel*/
            args->nBitsActual,    /* Actual number of bits/pixel */
            args->justify,        /* Pixel justification */
            "MONO",               /* Image representation */
            "SAR",                /* Image category */
            nBands,               /* Number of bands */
            bands,                /* Band information object list */
            &errorObj ))
    {
        nitf_Error_print(&errorObj, stderr, "Error setting up band source ");
        exit(EXIT_FAILURE);
    }

    return;
}
Esempio n. 26
0
void showTRE(nitf_TRE* tre)
{
    nitf_Error error;
    if (! nitf_TRE_print(tre, &error))
        nitf_Error_print(&error, stdout, "Ignoring...");
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
    char *vectorFile;                /* Vector file name */
    char *inputFile;                 /* Input file name */
    char *outputFile;                /* Output file name */
    FILE *vector;                    /* File stream for input vector */
    /* Arguments for new */
    test_nitf_ImageIOConstructArgs *newArgs;
    /* Arguments for read */
    test_nitf_ImageIOReadArgs *readArgs;
    char *errorStr;                  /* Error string */

    nitf_Record *record;           /* Record used for input and output */
    nitf_FileHeader *fileHdr;      /* File header */
    nitf_ImageSegment *imgSeg;     /* New image segment */
    nitf_Writer *writer;           /* Writer for output */
    nitf_ImageWriter *imgWriter;   /* Image writer */
    nitf_ImageSource *imgSource;   /* Image source */


    nitf_IOHandle out;               /* Handle for output */
    nitf_Error error;                /* Error object */
    nitf_Uint8 ***data;              /* Generated data [band][row][col] */

    if (argc < 4)
    {
        fprintf(stderr, "test_make_pattern vector input output\n");
        exit(-1);
    }
    vectorFile = argv[1];
    inputFile = argv[2];
    outputFile = argv[3];

    vector = fopen(vectorFile, "r");
    if (vector == NULL)
    {
        fprintf(stderr, "Error opening vector file %s\n", vectorFile);
        exit(-1);
    }

    newArgs = test_nitf_ImageIOReadConstructArgs(vector, &errorStr);
    if (newArgs == NULL)
    {
        fprintf(stderr, "%s\n", errorStr);
        return(-1);
    }

    fclose(vector);

    /*  Create the input record which will be used for output */

    record = readRecord(inputFile);

    /* Setup the image segment */

    imgSeg = nitf_Record_newImageSegment(record, &error);
    if (imgSeg == NULL)
    {
        nitf_Error_print(&error, stderr, "Error reading input ");
        exit(EXIT_FAILURE);
    }

    setupImageSubheader(newArgs, record, imgSeg);

    /*      Create Image */

    if (strcmp(newArgs->dataPattern, "brcI4") == 0)
    {
        data = (nitf_Uint8 ***) test_nitf_ImageIO_brcI4(newArgs, &errorStr);
        if (data == NULL)
        {
            fprintf(stderr, "%s\n", errorStr);
            exit(-1);
        }
    }
    else if (strcmp(newArgs->dataPattern, "brcC8") == 0)
    {
        data = (nitf_Uint8 ***) test_nitf_ImageIO_brcC8(newArgs, &errorStr);
        if (data == NULL)
        {
            fprintf(stderr, "%s\n", errorStr);
            exit(-1);
        }
    }
    else if (strncmp(newArgs->dataPattern, "blocks_", 7) == 0)
    {
        data = (nitf_Uint8 ***) test_nitf_ImageIO_block(newArgs, &errorStr);
        if (data == NULL)
        {
            fprintf(stderr, "%s\n", errorStr);
            exit(-1);
        }
    }
    else
    {
        fprintf(stderr, "Invalid pattern method %s\n");
        exit(-1);
    }

    /*      Create output file */

    out = nitf_IOHandle_create(outputFile,
                               NITF_ACCESS_WRITEONLY, NITF_CREATE | NITF_TRUNCATE, &error);
    if (NITF_INVALID_HANDLE(out))
    {
        nitf_Error_print(&error, stderr, "Error creating output file");
        exit(1);
    }

    writer = nitf_Writer_construct(&error);
    if (writer == NULL)
    {
        nitf_Error_print(&error, stderr, "Error creating writer object");
        exit(1);
    }

    if (!nitf_Writer_prepare(writer, record, out, &error))
    {
        nitf_Error_print(&error, stderr, "Error setting up write");
        exit(1);
    }

    imgWriter = nitf_Writer_newImageWriter(writer, 0, &error);
    if (imgWriter == NULL)
    {
        nitf_Error_print(&error, stderr, "Error setting up write");
        exit(1);
    }
    imgSource = makeImageSource(newArgs, (char ***) data);
    nitf_ImageWriter_setWriteCaching(imgWriter, 1);

    if (!nitf_ImageWriter_attachSource(imgWriter, imgSource, &error))
    {
        nitf_Error_print(&error, stderr, "Error setting up write");
        exit(1);
    }


    if (!nitf_Writer_write(writer, &error))
    {
        nitf_Error_print(&error, stderr, "Error writing up write");
        exit(1);
    }


    /* Destroy things */

    test_nitf_ImageIO_freeArray(data);
    nitf_IOHandle_close(out);
    exit(0);
}
Esempio n. 28
0
int main(int argc, char *argv[])
{
    nitf_Reader *reader;         /* Reader object */
    nitf_Record *record;         /* Record used for input and output */
    nitf_IOHandle in;            /* Input I/O handle */
    nitf_ListIterator imgIter;   /* Image segment list iterator */
    nitf_ListIterator imgEnd;   /* Image segment list iterator */
    nitf_ImageSegment *seg;      /* Image segment object */
    nitf_ImageSubheader *subhdr; /* Image subheader object */
    nitf_ImageReader *iReader;   /* Image reader */
    nitf_BlockingInfo *blkInfo;  /* Blocking information */

    static nitf_Error errorObj;  /* Error object for messages */
    nitf_Error *error;           /* Pointer to the error object */

    /*  Image information */

    char imageMode[NITF_IMODE_SZ+1]; /* Image (blocking) mode */

    /*  Mask structure and mask components */

    nitf_Uint32 imageDataOffset;    /* Offset to actual image data past masks */
    nitf_Uint32 blockRecordLength;  /* Block mask record length */
    nitf_Uint32 padRecordLength;    /* Pad mask record length */
    nitf_Uint32 padPixelValueLength; /* Pad pixel value length in bytes */
    nitf_Uint8 *padValue;           /* Pad value */
    nitf_Uint64 *blockMask;         /* Block mask array */
    nitf_Uint64 *padMask;           /* Pad mask array */
    size_t imgCtr = 0;
    const char* pathname;

    error = &errorObj;
    if (argc != 2)
    {
        fprintf(stderr, "Usage %s inputFile\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    pathname = argv[1];

    /*    Get the input record */

    in = nitf_IOHandle_create(pathname,
                              NITF_ACCESS_READONLY, NITF_OPEN_EXISTING, error);
    if (NITF_INVALID_HANDLE(in))
    {
        nitf_Error_print(error, stderr, "Error opening input ");
        exit(EXIT_FAILURE);
    }

    reader = nitf_Reader_construct(error);
    if (reader == NULL)
    {
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Error creating reader ");
        exit(EXIT_FAILURE);
    }

    record = nitf_Reader_read(reader, in, error);
    if (record == NULL)
    {
        nitf_Reader_destruct(&reader);
        nitf_IOHandle_close(in);
        nitf_Error_print(error, stderr, "Error reading input ");
        exit(EXIT_FAILURE);
    }

    /* Loop through the image segments */
    imgIter = nitf_List_begin(record->images);
    imgEnd = nitf_List_end(record->images);

    while (nitf_ListIterator_notEqualTo(&imgIter, &imgEnd))
    {
        /*  Get information from the image subheader */
        seg = (nitf_ImageSegment *) nitf_ListIterator_get(&imgIter);
        if (seg == NULL)
        {
            fprintf(stderr, "No Image segment\n");
            nitf_Reader_destruct(&reader);
            nitf_IOHandle_close(in);
            exit(EXIT_FAILURE);
        }
        subhdr = seg->subheader;

        nitf_Field_get(subhdr->imageMode,
                       imageMode, NITF_CONV_STRING, NITF_IMODE_SZ + 1, error);
        imageMode[NITF_IMODE_SZ] = 0;

        /*  Get an image reader which creates the nitf_ImageIO were the masks are */

        iReader = nitf_Reader_newImageReader(reader, imgCtr, NULL, error);
        if (iReader == NULL)
        {
            nitf_Reader_destruct(&reader);
            nitf_IOHandle_close(in);
            nitf_Record_destruct(&record);
            nitf_Error_print(error, stderr, "Error reading input ");
            exit(EXIT_FAILURE);
        }

        blkInfo = nitf_ImageReader_getBlockingInfo(iReader, error);
        if (blkInfo == NULL)
        {
            nitf_ImageReader_destruct(&iReader);
            nitf_Reader_destruct(&reader);
            nitf_IOHandle_close(in);
            nitf_Record_destruct(&record);
            nitf_Error_print(error, stderr, "Error reading input ");
            exit(EXIT_FAILURE);
        }

        /* Print the blocking information */

        printf("Image %s segment %zu:\n", pathname, imgCtr);
        printf("  Blocking (mode is %s):\n", imageMode);
        printf("    Block array dimensions (r,c) = %d %d\n",
               blkInfo->numBlocksPerRow, blkInfo->numBlocksPerCol);
        printf("    Block dimensions (r,c) = %d,%d\n",
               blkInfo->numRowsPerBlock, blkInfo->numColsPerBlock);
        printf("    Block length in bytes %zu\n", blkInfo->length);

        /*  Get the actual information */

        if (nitf_ImageIO_getMaskInfo(iReader->imageDeblocker,
                                     &imageDataOffset, &blockRecordLength,
                                     &padRecordLength, &padPixelValueLength,
                                     &padValue, &blockMask, &padMask))
        {
            nitf_Uint32 i;

            printf("  Masked image:\n");
            printf("    Image data offset = %d\n", imageDataOffset);
            printf("    Block and pad mask record lengths = %u %u\n",
                   blockRecordLength, padRecordLength);
            printf("    Pad value length = %u\n", padPixelValueLength);
            printf("    Pad value = ");
            for (i = 0;i < padPixelValueLength;i++)
            {
                printf("%x ", padValue[i]);
            }
            printf("\n");

            if (blockRecordLength != 0)
            {
                dumpMask("Block",
                         blockMask,
                         blkInfo->numBlocksPerRow,
                         blkInfo->numBlocksPerCol);
            }
            if (padRecordLength != 0)
            {
                dumpMask("Pad",
                         padMask,
                         blkInfo->numBlocksPerRow,
                         blkInfo->numBlocksPerCol);
            }
        }
        else
        {
            printf("Not a masked image\n");
        }

        nitf_ImageReader_destruct(&iReader);
        nrt_ListIterator_increment(&imgIter);
        ++imgCtr;
    }

    /*    Clean-up */
    nitf_Reader_destruct(&reader);
    nitf_IOHandle_close(in);
    nitf_Record_destruct(&record);
    return(0);
}