如何设置图像以便将其保存在 swift 2 中



嗨,我正在编写一个相机应用程序,当您按下照片按钮而不显示图片时,图片将保存到相机胶卷中。我快完成了,但是我有一段代码应该与 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)
}

当我尝试在保存它的函数中使用我刚刚创建的图像时,它不起作用。我该如何解决这个问题?

您的代码结构如下:

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)
}

我在我的项目中使用了这个代码片段:

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
}

最新更新