如何从CGImageRef获取PNG base64编码?

时间:2014-02-08 11:51:22

标签: objective-c macos png base64 cgimageref

我有CGImageRef对象(var quartzImage)。如何转换此对象以格式化web的PNG数据: “data:image / png; base64,”+ base64 data image

我的代码:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    CVPixelBufferLockBaseAddress(imageBuffer, 0);
    void *baseAddress = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
    CGImageRef quartzImage = CGBitmapContextCreateImage(context);
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    NSLog(@"%@",quartzImage);
}

2 个答案:

答案 0 :(得分:2)

如果您的代码中已有CGImageRef(名称为quartzImage),则无需创建NSImage。直接创建NSBitmapImageRep。在任何情况下都不应该使用lockFocus方法。这适用于应在屏幕上显示的图像。因此,lockFocus通常会为Retina屏幕创建分辨率为72 dpi和144 dpi的图像。或者您想使用屏幕属性为Web创建图像?试试这个:

NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:quartzImage];
NSData *repData = [bitmapRep representationUsingType:NSPNGFileType] properties:nil];
NSString *base64String = [repData base64EncodedStringWithOptions:0];

在OS X 10.9之前,此base64 ...方法不可用。在这种情况下,您应该使用base64Encoding

答案 1 :(得分:1)

NSImage *image = [NSImage imageWithCGImage:imageRef];
[image lockFocus];
NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, image.size.width, image.size.height)];
[image unlockFocus];
NSData *imageData = [bitmapRep representationUsingType:NSPNGFileType properties:nil];;
NSString *base64String = [imageData base64EncodedStringWithOptions:0];