1

我有 CGImageRef 对象(var quartzImage)。如何将此对象转换为 web 格式的 PNG 数据:"data:image/png;base64,"+ base64 数据图像

我的代码:

- (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);
}
4

2 回答 2

2

如果您已经有一个CGImageRefquartzImage在您的代码中有名称),那么您不需要创建一个NSImage. 直接创建一个NSBitmapImageRep。在任何情况下,您都不应该使用该lockFocus方法。这对于应显示在屏幕上的图像很有用。因此lockFocus通常会为 Retina 屏幕创建分辨率为 72 dpi 和 144 dpi 的图像。或者您想使用您的屏幕属性为网络创建图像?尝试这个:

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

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

于 2014-02-08T15:59:41.323 回答
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];
于 2014-02-08T11:57:49.590 回答