如何在cocos3d拍摄相机

时间:2012-05-22 10:30:29

标签: iphone objective-c xcode cocos3d

我制作了一个增强现实应用程序,我需要从相机拍照并在上面叠加3D模型。

我已经可以截取带有3d徽标的gl视图截图,但我无法弄清楚如何从相机拍摄图像。

如何从相机拍照?

1 个答案:

答案 0 :(得分:0)

如果您要显示实时视频流形式的相机,可以使用GPUImage

如果您只需要拍摄静止图像,请使用AVFoundation的AVCaptureStillImageOutput。请参阅AVCam - Apple's sample code,您可以在其中删除预览实时视频(AVCaptureVideoPreviewLayer)的部分,并在需要时捕获静态图片。

//you'll need to create an AVCaptureSession

_session = [[AVCaptureSession alloc] init];

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

//there are steps here where you adjust capture device if needed

NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];

if ([device supportsAVCaptureSessionPreset: AVCaptureSessionPreset640x480]) {
    _session.sessionPreset = AVCaptureSessionPreset640x480;
}

_stillImageOutput = [[AVCaptureStillImageOutput alloc] init];

NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
[_stillImageOutput setOutputSettings:outputSettings];
[outputSettings release];

AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in _stillImageOutput.connections) {
   for (AVCaptureInputPort *port in [connection inputPorts]) {
       if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
            videoConnection = connection;
           break;
       }
   }
   if (videoConnection) { break; }
}

[_session addOutput: _stillImageOutput];

[_session startRunning];

此代码用于拍照:

AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in _stillImageOutput.connections)
{
    for (AVCaptureInputPort *port in [connection inputPorts])
    {
        if ([[port mediaType] isEqual:AVMediaTypeVideo] )
        {
            videoConnection = connection;
            break;
        }
    }
    if (videoConnection) { break; }
}

[_stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {

    if (imageSampleBuffer != NULL) {
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
        UIImage *image = [UIImage imageWithData: imageData];
        //do something with image or data
    }
}

希望它有所帮助。