views:

317

answers:

2

the pointer data if pointing to some image generated by an iphone application. Does anybody now if using CGBitmapContextCreate make a copy of this data or does it use the image "in place"?

Ideally, I'd like to reuse the information in data* and not create any additional copy of this image.

void* data = <my data>;

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef imageContext = CGBitmapContextCreate(data, w, h, 8, w*8, colorSpace, kCGBitmapByteOrder32Big|kCGImageAlphaPremultipliedLast);
CGImageRef imageRef = CGBitmapContextCreateImage(imageContext);
UIImage* image =[[UIImage alloc] initWithCGImage:imageRef];

More generally, this method of creating image seems rather convoluted to me. Does anybody knows what's going on here? Is there any easier way to create UIImage?

Thanks

+2  A: 

What about something like this:

void * data = <my data>;
NSData * newData = [NSData dataWithBytesNoCopy:data length:lengthOfData];
UIImage * image = [[UIImage alloc] initWithData:newData];
Dave DeLong
-[UIImage initWithData] decodes the image data and in the process makes a copy of it. To truly create an image without allocating memory, the only way is to have the data predecoded in a pixel format the iPhone supports copy-on-write with and use CGBitmapContextCreate
rpetrich
Actually I couldn't get that to work properly... How do I pass the format and size information to the UIImage? Surely something is missing there.
+2  A: 

From here it looks like CGBitmapContextCreate will just use the memory you passed in. But the data may be copied by the call to CGBitmapContextCreateImage,

Apple docs:

Discussion The CGImage object returned by CGBitmapContextCreateImage is created by a copy operation. Subsequent changes to the bitmap graphics context do not affect the contents of the returned image. In some cases the copy operation actually follows copy-on-write semantics, so that the actual physical copy of the bits occur only if the underlying data in the bitmap graphics context is modified. As a consequence, you may want to use the resulting image and release it before you perform additional drawing into the bitmap graphics context. In this way, you can avoid the actual physical copy of the data.

Skrymsli