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

すでに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];

この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 に答える