【问题标题】:iOS: How can a custom camera save images always in the right orientation?iOS:自定义相机如何始终以正确的方向保存图像?
【发布时间】:2017-04-27 05:13:20
【问题描述】:

我目前正在使用 IOS 实现自定义摄像头。我希望相机始终以正确的方向将图像保存到相册,就像官方 iOS 相机一样:无论您以什么方向握住相机,您始终可以看到照片保存正确的方向。 我检查了许多源代码,他们似乎使用以下内容相当随意地保存了图像:

var image  = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.right)

但这仅在设备直立时有效 有人可以提供任何建议吗?

我也尝试过定位

let uiorientation = UIApplication.shared.statusBarOrientation

但是当屏幕纵向锁定时它总是返回纵向。

【问题讨论】:

    标签: ios iphone


    【解决方案1】:

    当您获得UIImage 对象时,您必须更新图像旋转。 将从图像选择器获取的图像传递给此方法

    斯威夫特

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

    目标-C

    +(UIImage *)getNormalizedImage:(UIImage *)rawImage {
    
        if(rawImage.imageOrientation == UIImageOrientationUp)
        return rawImage;
    
        UIGraphicsBeginImageContextWithOptions(rawImage.size, NO, rawImage.scale);
        [rawImage drawInRect:(CGRect){0, 0, rawImage.size}];
        UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return normalizedImage;
    }
    

    【讨论】:

    • 谢谢,但这不是我想要的。我从 AVCapture 委托中的捕获方法获取 CGImage。其中没有有效的方向信息(方向总是向上)。我需要通过检测设备/接口的方向来分配方向
    • 您可以将 cgimage 转换为 UIimage 并设置默认方向 = .up
    猜你喜欢
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    相关资源
    最近更新 更多