识别(读取)图片二维码

  1. 二维码读取包括:
    1. 直接对静态的图片进行二维码识别,最低支持iOS8.0
    2. 利用摄像头扫描识别(动态图片),需要真机设备

读取图片二维码 <- swift

  1. 导入框架(可选)

    import CoreImage
    
  2. 实现代码

    @IBOutlet weak var qrCodeImage: UIImageView!
    
    override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
        // 0. 创建一个上下文
        let context = CIContext()
    
        // 1. 创建一个二维码探测器
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: context, options: [CIDetectorAccuracy : CIDetectorAccuracyHigh])
    
        // 2. 探测二维码图片的特征
        guard let image = qrCodeImage.image else {
            return
        }
        let imageCI = CIImage(image: image)
        let features = detector.featuresInImage(imageCI!)
    
        // 3. 处理识别到的特征值
        for feature in features {
    
            if feature.isKindOfClass(CIQRCodeFeature) {
                let qrCodeFeature = feature as! CIQRCodeFeature
    
                print(qrCodeFeature.messageString)
    
                // 绘制识别到的二维码图片,详见“5.识别二维码- 描绘边框”
            }
        }
    
        // 将重新绘制的图片显示(可选),没绘制可以不设置
        // qrCodeImage.image = tempImage
    
        // 4. 弹框显示内容
        // 4.1 创建弹框控制器
        let alterVC = UIAlertController(title: "结果", message: resultStrs.description, preferredStyle: UIAlertControllerStyle.Alert)
    
        // 4.2 给控制器设置行为
        let action = UIAlertAction(title: "关闭", style: UIAlertActionStyle.Default) { (action: UIAlertAction) in
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    
        // 4.3 添加行为
        alterVC.addAction(action)
    
        // 4.4 弹出提示内容
        presentViewController(alterVC, animated: true, completion: nil)
    }
    

你可能感兴趣的:(识别(读取)图片二维码)