[英]What is the correct way to return an image from a C function?
I'm new to C trying to understand the basics.我是 C 的新手,试图了解基础知识。
I am wanting to call a function that creates and returns a jpeg image.我想调用一个 function 来创建并返回一个 jpeg 图像。
In some other language like Python you would just put the return value from the function into a variable.在像 Python 这样的其他语言中,您只需将 function 的返回值放入变量中。 C obviously does not work that way. C 显然不能那样工作。
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?那么对于一个 function 向另一个请求 jpeg 图像并接收该图像的正确方法是什么,该图像的大小未知?
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?创建一个定义指向缓冲区和长度的指针的结构,然后在两个函数的 scope 之外设置一个变量,以便两个函数都可以访问数据的正确方法是正确的方法吗?
Presumably I also need to properly free the memory used inside the makeimg function via tjFree(&_compressedImage);
大概我还需要通过tjFree(&_compressedImage);
I copied the code for this function from somewhere on the net.我从网上某处复制了这个 function 的代码。 It creates a jpeg function.它创建一个 jpeg function。 I want to get the resulting jpeg back.我想取回生成的 jpeg。
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.我是 C 的初学者(有 Python 经验),所以如果您能尽可能多地解释您的回复,我们将不胜感激。
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.如果您不需要多个错误代码,将图像参数设置为 null 并检查它可能就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.