Search code examples
cpnglibpng

read a png image in buffer


hi i have used libpng to convert grayscale png image to raw image using c. in that lib the function png_init_io needs file pointer to read the png. but i pass the png image as buffer is there any other alternative functions to to read png image buffer to raw image. please help me

int read_png(char *file_name,int *outWidth,int *outHeight,unsigned char **outRaw)  /* We need to open the file */
{
......
/* Set up the input control if you are using standard C streams */
   png_init_io(png_ptr, fp);
......
}

instead i need this like

int read_png(unsigned char *pngbuff, int pngbuffleng, int *outWidth,int *outHeight,unsigned char **outRaw)  /* We need to open the file */
{
}

Solution

  • From the manual of png_init_io, it is apparent that you can override the read function with png_set_read_fn.

    Doing this, you can fool png_init_io into thinking that it is reading from a file, while in reality you're reading from a buffer:

    struct fake_file
    {
        unsigned int *buf;
        unsigned int size;
        unsigned int cur;
    };
    
    static ... fake_read(FILE *fp, ...) /* see input and output from doc */
    {
        struct fake_file *f = (struct fake_file *)fp;
        ... /* read a chunk and update f->cur */
    }
    
    struct fake_file f = { .buf = pngBuff, .size = pngbuffleng, .cur = 0 };
    /* override read function with fake_read */
    png_init_io(png_ptr, (FILE *)&f);