我想将此函数从 obj c 转换为 swift,但我无法转换部分代码。 有人可以向我解释如何从 AVFondation 拍照或帮助我翻译此功能吗?
- (void) capImage { //method to capture image from AVCaptureSession video feed
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;
}
}
NSLog(@"about to request a capture from: %@", stillImageOutput);
[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
if (imageSampleBuffer != NULL) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
[self processImage:[UIImage imageWithData:imageData]];
}
}]; }
我做了什么但没有工作:
func takePhoto(sender:UIButton){
var videoConnection:AVCaptureConnection
var connection:AVCaptureConnection
var port : AVCaptureInputPort
for connection in stillImageOutput?.connections {
for (port in connection.inputPorts as AVCaptureInputPort) {
if port = AVMediaTypeVideo {
videoConnection = connection
break
}
}
if videoConnection {
break
}
}
stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(imageSampleBuffer, error) in
if (imageSampleBuffer != nil) {
var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer as CMSampleBuffer)
var image: UIImage = UIImage(data: imageData)
}
})
}
有人可以帮我吗?
最佳答案
由于上面的代码不起作用,我在 Swift 中找到了一个优雅的解决方案。
取而代之的是:
var videoConnection : AVCaptureConnection?
for connection in self.stillImageOutput.connections{
for port in connection.inputPorts!{
if port.mediaType == AVMediaTypeVideo{
videoConnection = connection as? AVCaptureConnection
break //for ports
}
}
if videoConnection != nil{
break //for connections
}
}//take a photo then
你应该使用这个:(针对“输出”拼写错误进行了更新)
if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo){//take a photo here}
希望对您有所帮助!
关于ios - swift : take photo from AVFoundation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25871513/