您好我正在编写一个相机应用程序,当您按下照片按钮而不显示照片时,照片将被保存到相机中。我差不多完成了,但我遇到了一段代码应该与swift一起工作的问题,但是不能使用swift 2。
func didTakePhoto() {
if let videoConection = stillImageOutput2?.connectionWithMediaType(AVMediaTypeVideo){
videoConection.videoOrientation = AVCaptureVideoOrientation.Portrait
stillImageOutput2?.captureStillImageAsynchronouslyFromConnection(videoConection, completionHandler: { (sampleBuffer, ErrorType) -> Void in
if sampleBuffer != nil {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let dataProvider = CGDataProviderCreateWithCFData(imageData)
let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, .RenderingIntentDefault)
var savedImage = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
}
})
}
}
@IBAction func takePhotoBtn(sender: UIButton) {
didTakePhoto()
UIImageWriteToSavedPhotosAlbum(savedImage, nil, nil, nil)
}
当我尝试使用我刚刚在保存它的函数中创建的图像时,它不起作用。我该如何解决这个问题?
答案 0 :(得分:1)
您的代码结构如下:
func didTakePhoto() {
// ...
var savedImage = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
}
@IBAction func takePhotoBtn(sender: UIButton) {
didTakePhoto()
UIImageWriteToSavedPhotosAlbum(savedImage, nil, nil, nil)
}
所以savedImage
在本地声明,因此完全局限于didTakePhoto()
的世界。在takePhotoBtn
的世界中,不存在savedImage
- 因此您会遇到编译器错误。
你有两个选择。您可以在两个方法都能看到的更高级别声明savedImage
:
var savedImage:UIImage!
func didTakePhoto() {
// ...
savedImage = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
}
@IBAction func takePhotoBtn(sender: UIButton) {
didTakePhoto()
UIImageWriteToSavedPhotosAlbum(savedImage, nil, nil, nil)
}
或者,您可以didTakePhoto
返回 savedImage
作为结果:
func didTakePhoto() -> UIImage {
// ...
let savedImage = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
return savedImage
}
@IBAction func takePhotoBtn(sender: UIButton) {
UIImageWriteToSavedPhotosAlbum(didTakePhoto(), nil, nil, nil)
}
答案 1 :(得分:0)
我在我的项目中使用此代码段:
func saveImage(image: UIImage)
let destinationPath = documentsPath.stringByAppendingPathComponent("test.png")
UIImagePNGRepresentation(rotateImage(image))!.writeToFile(destinationPath, atomically: true)
}
func rotateImage(image: UIImage) -> UIImage {
print(image.imageOrientation.hashValue )
if (image.imageOrientation == UIImageOrientation.Up ) {
return image //UIImage(CGImage: image, scale: 0.5, orientation: UIImageOrientation.Up)
}
UIGraphicsBeginImageContext(image.size)
image.drawInRect(CGRect(origin: CGPoint.zero, size: image.size))
let copy = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return copy
}