How to scan Qr code from an image picked with UIImagePickerController in iOS

别来无恙 提交于 2019-12-21 17:27:13

问题


I am able to scan qr code with camera without using any external libraries like ZBAR or ZXING.

Now what I actually want is to let the user upload an image from photo library and get the qr code scanned from that uploaded image.

I know how to use UIImagePickerController (used it before).

What I want to ask is that, How can I scan qr code from an uploaded image (without using the camera)

You can suggest some code (.h / .m files) that I can add in my project.

Please don't suggest me any external libraries like ZBAR or ZXING.


回答1:


I know you might have found solution for this but i am replying to the post if my answer may help other for relevant question.

Here I am posting my code to ScanQRCode from image picked from gallery without using any Library.

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {



    if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
                 let detector:CIDetector=CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])

    let ciImage:CIImage = CIImage(image:pickedImage)!

    var qrCodeLink = ""

    let features=detector.featuresInImage(ciImage)

    for feature in features as! [CIQRCodeFeature] {

        qrCodeLink += feature.messageString
    }

    print(qrCodeLink)//Your result from QR Code
}

    dismissViewControllerAnimated(true, completion: nil)
}



回答2:


Updated to swift 5 and more "swifty" way based on @Dev_Tandel response.
But for me .originalImage worked instead of .editedImage.

func imagePickerController(_ picker: UIImagePickerController,
                           didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    guard let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage,
        let detector = CIDetector(ofType: CIDetectorTypeQRCode,
                                  context: nil,
                                  options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]),
        let ciImage = CIImage(image: pickedImage),
        let features = detector.features(in: ciImage) as? [CIQRCodeFeature] else { return }

    let qrCodeLink = features.reduce("") { $0 + ($1.messageString ?? "") }

    print(qrCodeLink)//Your result from QR Code
}



回答3:


In Apple's iOS, a QR code reader is not natively included. Therefore there is no API from Apple you can use.

You have to rely either or third party SDKs or write your own code.



来源:https://stackoverflow.com/questions/24844086/how-to-scan-qr-code-from-an-image-picked-with-uiimagepickercontroller-in-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!