我是C语言的新手,正在尝试理解基础知识。
我想调用一个创建并返回jpeg图像的函数。
在其他语言中,如Python,您只需将函数的返回值放入变量中即可。很明显,C不是这样工作的。
那么,一个函数向另一个函数请求jpeg图像并接收回未知大小的图像的正确方法是什么?
创建一个定义指向缓冲区和长度的指针的结构,然后在这两个函数的作用域之外设置一个变量,这样两个函数都可以访问数据,这是正确的方法吗?
假设我还需要通过tjFree(&_compressedImage);适当地释放在makeimg函数中使用的内存
我从网上的某个地方复制了这个函数的代码。它创建了一个jpeg函数。我想拿回生成的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);
}任何关于采取好的方法的指导都是值得赞赏的。
我是一个C语言的初学者(有Python的经验),所以如果你能尽可能多地解释你的回应,我将不胜感激。
发布于 2019-09-24 12:32:50
有多种方法可以做到这一点。我更喜欢以下内容:
/*
* 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;
}如果您不需要多个错误码,将image参数设置为null并进行检查可能就足够了。
https://stackoverflow.com/questions/58073059
复制相似问题