问题
Is there a way to store and load raw image data on disk in iOS in order to save time and memory on decompression and reduce app's dirty memory footprint?
Paul Haddad has been hinting to something like this and I understand that this technique is used for efficient game texture loading with OpenGL.
My use case if for user supplied full screen wallpaper, that is always displayed in the background. Currently I save it to PNG and load it during app startup. This wastes memory and CPU for decompressing the image. I would like to save the image and then later load it as memory mapped file. Is there a way to achieve this in CoreGraphics/UIKit land?
回答1:
I have used this to save slices of the video buffer in real time
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CVPixelBufferLockBaseAddress(imageBuffer,0);
bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
size_t sliceSize = bytesPerRow*sliceWidth*sizeof(char);
int slicePos= bytesPerRow*sliceStart*sizeof(char);
NSData *rawFrame = [NSData dataWithBytes:(void*)baseAddress+slicePos length:sliceSize];
inputPath = [NSString stringWithFormat:@"%@%@%d", NSTemporaryDirectory(), @"slice",step];
[[NSData dataWithData:rawFrame] writeToFile:inputPath atomically:NO];
}
Then I read it back with
-(void)readSlice
{
//read slice i
NSString *filePath = [NSString stringWithFormat:@"%@%@%d", NSTemporaryDirectory(), @"slice",i];
char* imgD= (char*)malloc(sliceSize);
[[NSData dataWithContentsOfFile:filePath] getBytes:imgD];
CGContextRef context = CGBitmapContextCreate(imgD, sliceHeight,sliceWidth, 8, bytesPerRad, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGImageRef quartzImage = CGBitmapContextCreateImage(context);
CGContextRelease(context);
free(imgD);
//do something with quartzImage
}
来源:https://stackoverflow.com/questions/13253057/uiimage-cgimage-with-memory-mapped-raw-data