2

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 */
{
}
Siva
  • 249
  • 5
  • 23
  • Your question is not very clear (and lack of uppercase and punctuation does not help). You mean that you want to read the PNG image from memory? The `pngbuff` buffer contains the same bytes that a PNG file? – leonbloy Mar 14 '13 at 13:35
  • @leonbloy yes absolutely you are right.. please help me is there any other function – Siva Mar 14 '13 at 13:39
  • Then I'm voting to close as duplicate. See the answer there: http://blog.hammerian.net/2009/reading-png-images-from-memory/ – leonbloy Mar 14 '13 at 13:40
  • possible duplicate of [libpng load file from memory buffer](http://stackoverflow.com/questions/14547765/libpng-load-file-from-memory-buffer) – leonbloy Mar 14 '13 at 13:40
  • @leonbloy i already saw this but it is not clear to me.. i am new to this. if give some simple test program for png_set_read_fn as well png_set_write_fn i will be thankful to u. – Siva Mar 14 '13 at 13:48
  • Did you solve your problem and can you show the full example? I'm trying to solve a similar issue but with `libbpg` library (it also uses `png_init_io` function) - https://stackoverflow.com/questions/53315767/libbpg-how-to-pass-bytes-instead-of-file-path – user924 Nov 15 '18 at 10:51

1 Answers1

3

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);
Shahbaz
  • 42,684
  • 17
  • 103
  • 166