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

How do I set an image so I can save it in 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 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
}

您的代码结构如下:

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