将UIImage转换为CIImage时,从UIImage进行QR码检测失败

时间:2018-08-10 10:43:18

标签: swift uiimage qr-code

我正在尝试解码QR码以获取其内容。以下是它的代码:

func detectQRCode(_ recImage: UIImage?) -> [CIFeature]?
{
    if let img = recImage,
    let ciImage = CIImage.init(image: img)
    {
        var options: [String: Any]
        let context = CIContext()
        options = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
        let qrDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: options)
        if ciImage.properties.keys.contains((kCGImagePropertyOrientation as String))
        {
            options = [CIDetectorImageOrientation: ciImage.properties[(kCGImagePropertyOrientation as String)] ?? 1]
        }
        else
        {
            options = [CIDetectorImageOrientation: 1]
        }
        let features = qrDetector?.features(in: ciImage, options: options)
        return features
    }
    return nil
}

如果let语句在let ciImage = CIImage.init(image: img)处失败。请提出建议。

1 个答案:

答案 0 :(得分:0)

请尝试从ciImage的属性中获取UIImage,例如-

if let ciImage = recImage?.ciImage

更新后的代码应如下所示-

func detectQRCode(_ recImage: UIImage?) -> [CIFeature]?
{
    if let ciImage = recImage?.ciImage
    {
        var options: [String: Any]
        let context = CIContext()
        options = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
        let qrDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: options)
        if ciImage.properties.keys.contains((kCGImagePropertyOrientation as String))
        {
            options = [CIDetectorImageOrientation: ciImage.properties[(kCGImagePropertyOrientation as String)] ?? 1]
        }
        else
        {
            options = [CIDetectorImageOrientation: 1]
        }
        let features = qrDetector?.features(in: ciImage, options: options)
        return features
    }
    return nil
}