UIImage Orientation Swift

时间:2015-01-29 21:55:31

标签: ios swift uiimage avfoundation alassetslibrary

我已编写此代码以使用Swift中的AVFoundation库捕获图像:

@IBAction func cameraButtonWasPressed(sender: AnyObject) {

    if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo){
        stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection){
            (imageSampleBuffer : CMSampleBuffer!, _) in

            let imageDataJpeg = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer)

            var pickedImage: UIImage = UIImage(data: imageDataJpeg)!

            let library = ALAssetsLibrary()
            library.writeImageToSavedPhotosAlbum(pickedImage.CGImage,
                metadata:nil,
                completionBlock:nil)

        }


    }

}

它工作正常,但当我去照片库时,图像逆时针旋转90度。

有人可以给我一个关于在哪里挖掘以解决这个问题的提示吗?

3 个答案:

答案 0 :(得分:2)

您应该使用稍微不同的writeImage方法:

(1)从UIImage imageOrientation属性(枚举)获取方向,并将其强制转换为ALAssetOrientation(与UIImageOrientation具有相同Int值的枚举)

 var orientation : ALAssetOrientation = ALAssetOrientation(rawValue:           
                                        pickedImage.imageOrientation.rawValue)!

(2)在ALAssetLibrary上使用类似但不同的方法

library.writeImageToSavedPhotosAlbum(
                pickedImage.CGImage,
                orientation: orientation,
                completionBlock:nil)

这适用于我在Objective-C 中的 ...我已经快速转换到Swift(如上所述),但我收到编译器警告。

  

无法调用' writeImageToSavedPhotosAlbum'使用类型'的参数列表(CGImage!,orientation:ALAssetOrientation,completionBlock:NilLiteralConvertible)'

也许你可以尝试(我没有时间在Swift中构建一个完整的AVFoundation管道来进行最终测试)

如果无法使其工作,另一种解决方案是从sampleBuffer中提取exif元数据并将其传递给您已使用的方法

library.writeImageToSavedPhotosAlbum(pickedImage.CGImage, metadata:nil, completionBlock:nil

答案 1 :(得分:2)

也许这个Swift代码可以帮助你。

//correctlyOrientedImage.swift

import UIKit

extension UIImage {

    public func correctlyOrientedImage() -> UIImage {
        if self.imageOrientation == UIImageOrientation.Up {
            return self
        }

        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        self.drawInRect(CGRectMake(0, 0, self.size.width, self.size.height))
        var normalizedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return normalizedImage;
    }
}

我看到它somewhere in stack overflow并将其纳入我的项目中。

答案 2 :(得分:0)

斯威夫特 5

extension UIImage {
    public func correctlyOrientedImage() -> UIImage {
        if self.imageOrientation == UIImage.Orientation.up {
            return self
        }
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()!;
        UIGraphicsEndImageContext();

        return normalizedImage;
    }
}