I'm new to C trying to understand the basics.
I am wanting to call a function that creates and returns a jpeg image.
In some other language like Python you would just put the return value from the function into a variable. C obviously does not work that way.
What is the correct way then for one function to ask another for a jpeg image and to receive back that image, which is of an unknown size?
Is the correct way to create a struct that defines a pointer to a buffer and a length, and then to set a variable outside the scope of both functions, so that both functions can access the data?
Presumably I also need to properly free the memory used inside the makeimg function via tjFree(&_compressedImage);
I copied the code for this function from somewhere on the net. It creates a jpeg function. I want to get the resulting jpeg back.
static void makeimg() {
const int JPEG_QUALITY = 75;
const int COLOR_COMPONENTS = 3;
int _width = 1920;
int _height = 1080;
long unsigned int _jpegSize = 0;
unsigned char* _compressedImage = NULL; //!< Memory is allocated by tjCompress2 if _jpegSize == 0
unsigned char buffer[_width*_height*COLOR_COMPONENTS]; //!< Contains the uncompressed image
tjhandle _jpegCompressor = tjInitCompress();
tjCompress2(_jpegCompressor, buffer, _width, 0, _height, TJPF_RGB,
&_compressedImage, &_jpegSize, TJSAMP_444, JPEG_QUALITY,
TJFLAG_FASTDCT);
tjDestroy(_jpegCompressor);
//to free the memory allocated by TurboJPEG (either by tjAlloc(),
//or by the Compress/Decompress) after you are done working on it:
tjFree(&_compressedImage);
}
Any guidance on a good approach to take appreciated.
I am a beginner with C (experienced with Python), so if you could please explain as much as possible about your response it would be much appreciated.
There are multiple ways of doing this. I prefer the following:
/*
* Makes an image and returns the length
* returns < 0 on error
*
* Call as follows:
* char *image ;
* int len = make_image( &image );
* if (len < 0) { /* Process error code */ }
*/
int makeImage(void **image) {
unsigned char *_image ;
int length ;
/* Create image and set the length of buffer in length variable */
/* Return the image */
*image = _image ;
return length;
}
If you do not need multiple error codes, setting image parameter to null and checking for it may be enough.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.