tags:

views:

104

answers:

2
+1  Q: 

Saving PNG images

I'm having trouble saving png images.

I want to add some binary data into the png file, such as the following structure.

struct Foo
{
     int value;
     char str[10];
     double val;
     double val2;
};

It seems to save just fine with the following code. However, when I later load up the png file, I see that my chunk has not been saved, its gone. What am I doing wrong? My needs are simple, I just want to embed a little bit of extra binary information with the image itself.

Foo foo;

png_unknown_chunk chunks[1];
strcpy((png_charp)chunks[0].name, "fFoo");
chunks[0].data = &foo;
memcpy(chunks[0].data,&foo,sizeof(Foo)*1);
chunks[0].size = sizeof(Foo);
png_set_unknown_chunks(png_ptr, info_ptr, chunks, 1);

printf("1: %d\n",(int)info_ptr->unknown_chunks_num);
for (int n = 0; n < info_ptr->unknown_chunks_num; ++n)
{
    tag_pngmeta p;
    memcpy(&p,info_ptr->unknown_chunks[n].data,info_ptr->unknown_chunks[n].size);

    printf("2: %s,%d\n",info_ptr->unknown_chunks[n].name, 
        (int)info_ptr->unknown_chunks[n].size);

    printf("3: %s\n",p.name);
}

The above shows that that the buffer was updatted properly and my data is embedded into the image.I

However, when I later load it up, its gone. Heres how I load it up again from a saved png.

png_unknown_chunkp unknowns;
int num_unknowns = (int)png_get_unknown_chunks(png_ptr, info_ptr, &unknowns);
printf("%d-----\n",(int)num_unknowns);

printf("%d\n",(int)info_ptr->unknown_chunks_num);
for (int n = 0; n < info_ptr->unknown_chunks_num; ++n)
{
    printf("%s,%d\n",info_ptr->unknown_chunks[n].name,  (int)info_ptr->unknown_chunks[n].size);
}

Foo has disappered.

+1  A: 

http://www.libpng.org/pub/png/libpng-1.2.5-manual.html says:

You can use the png_set_unknown_chunks function to queue up chunks for writing. You give it a chunk name, raw data, and a size; that's all there is to it. The chunks will be written by the next following png_write_info_before_PLTE, png_write_info, or png_write_end function. Any chunks previously read into the info structure's unknown-chunk list will also be written out in a sequence that satisfies the PNG specification's ordering rules.

Are you calling any of the three png_write_* functions it mentions? png_set_unknown_chunks doesn't seem to do the write itself.

Scott Wolchok
A: 

Yep, looks like the write isn't actually called (as the fp mentioned). Also, according to a definition of png_unknown_chunk...

typedef struct png_unknown_chunk_t {
    png_byte name[5];
    png_byte *data;
    png_size_t size;
} png_unknown_chunk;

You don't need to perform the first memcpy

memcpy(chunks[0].data,&foo,sizeof(Foo)*1);

as the previous line has already set the chunk's data pointer to the location of foo. Be aware though that foo has been defined on the stack for this function so the write must be performed inside this function to ensure that foo is still valid.

roguenut