我想保留在函数void ManipulateImagePixelData(CGImageRef inImage)
中分配的内存块(有关完整代码,请参阅http://developer.apple.com/library/mac/#qa/qa1509/_index.html)
void ManipulateImagePixelData(CGImageRef inImage)
{
// Create the bitmap context
CGContextRef cgctx = CreateARGBBitmapContext(inImage);
if (cgctx == NULL)
{
// error creating context
return;
}
// Get image width, height. We'll use the entire image.
size_t w = CGImageGetWidth(inImage);
size_t h = CGImageGetHeight(inImage);
CGRect rect = {{0,0},{w,h}};
// Draw the image to the bitmap context. Once we draw, the memory
// allocated for the context for rendering will then contain the
// raw image data in the specified color space.
CGContextDrawImage(cgctx, rect, inImage);
// Now we can get a pointer to the image data associated with the bitmap
// context.
void *data = CGBitmapContextGetData (cgctx);
if (data != NULL)
{
// **** You have a pointer to the image data ****
// **** Do stuff with the data here ****
}
// When finished, release the context
CGContextRelease(cgctx);
// Free image data memory for the context
if (data)
{
free(data);
}
}
我修改了这个函数,以便我有宽度和高度,但是我没有设法让内存块data
指向。
我的功能如下:
void ManipulateImagePixelData(CGImageRef inImage,
unsigned long * width, unsigned long * height, void * copy)
我不再在最后释放数据,并承担以后释放数据的责任。
我以为我可以做这样简单的事情:
(caller)
void * rawPixels=NULL;
ManipulateImagePixelData([obj CGImageForProposedRect:NULL context:[NSGraphicsContext currentContext] hints:nil],&imgWidth1, &imgHeight1, rawPixels)];
(ManipulateImagePixelData function)
void * pixels = CGBitmapContextGetData (cgctx);
if (pixels != NULL) {
*width=w;
*height=h;
copy=pixels;
[...]
并且rawPixels指向上述块,但此调用后rawPixels
仍为NULL。我有点困惑,我的C技能有点生疏。
我该怎么做才能获得数据?
答案 0 :(得分:2)
您应该将ManipulateImagePixelData
指向变量的指针传递给您,以获取在函数中分配的缓冲区的地址:
void ManipulateImagePixelData(CGImageRef inImage, unsigned long * width, unsigned long * height, void ** copy) {
...
void* data = CGBitmapContextGetData (cgctx);
*copy = data; // copy the output parameter
...
}
并将其称为:
void * rawPixels=NULL;
ManipulateImagePixelData([obj CGImageForProposedRect:NULL context:[NSGraphicsContext currentContext] hints:nil],&imgWidth1, &imgHeight1, &rawPixels)];
更好的是,您可以这样定义:
void* ManipulateImagePixelData(CGImageRef inImage, unsigned long * width, unsigned long * height) {
...
void* data = CGBitmapContextGetData (cgctx);
...
return data;
}