How do I save an image to a buffer in memory? The following C code shows how to save a gd image to a memory buffer, and then write that buffer to a file on disk. You could also write it directly to stdout, preceded by a Content-type: image/png header and two CR/LF sequences, to directly return an image from a CGI program.
Note to Borland C++ programmers: this code will allow you to save an image using the bgd.dll library, because no FILE * objects are passed across the DLL boundary.
For your convenience, gd allocates the buffer for you; when you are done with it, you must call gdFree to release it.
Of course, there is a gdImageJpegPtr function available as well. This particular example saves a PNG image. #include #include #include
void mySavePng(char *filename, gdImagePtr im) { FILE *out; int size; char *data; out = fopen("filename, "wb"); if (!out) { /* Error */ } data = (char *) gdImagePngPtr(im, &size); if (!data) { /* Error */ } if (fwrite(data, 1, size, out) != size) { /* Error */ } if (fclose(out) != 0) { /* Error */ } gdFree(data); }
CodeGuru Forums > Visual C++ & C++ Programming > C++ (Non Visual C++ Issues) Binary data from void * to std::string?
#1 July 13th, 2007, 02:05 PM bakani Junior Member Join Date: Jul 2007, Posts: 2 Reputation:
Binary data from void * to std::string? Hi,
I'm currently trying to use the GD library. I want to create an image in memory and put that image into a std::string for output using an stream.
void *str = gdImageJpegPtr(im, &size, -1);
size is an integer that contains the size of the actual data str is a pointer to the data in memory
What is the best way to get that binary data into a std::string?
Thank you for your help
Alex
#2 July 13th, 2007, 02:26 PM ZuK Member + Join Date: Oct 2002, Posts: 639 Location: Austria Reputation:
Re: Binary data from void * to std::string? I don't think that it is very useful to store binary data in a string. If all you want to do is save the data in an output stream then I would use ofstream::write. something like this
#3 July 13th, 2007, 03:13 PM HighCommander4 Senior Member Join Date: Apr 2004, Posts: 1,087 Location: Canada Reputation:
Re: Binary data from void * to std::string? You can put it into an std::string quite easily.
Code: void *str = gdImageJpegPtr(im, &size, -1); std::string s(static_cast(str), static_cast(str) + size); __________________ Rewards come to those who persist after others have given up.
#4 July 13th, 2007, 04:03 PM bakani Junior Member Join Date: Jul 2007, Posts: 2 Reputation:
Re: Binary data from void * to std::string? Thank you very much! That did the trick.
Alex
« Previous Thread | Next Thread »
CodeGuru Forums > Visual C++ & C++ Programming > C++ (Non Visual C++ Issues) Binary data from void * to std::string?