在Swift iOS中扫描后如何获取二维码图像?

时间:2019-05-11 08:31:19

标签: ios swift image qr-code

我正在迅速地用Xcode开发一个二维码阅读器应用程序。我用以下代码扫描了二维码:

import UIKit
import AVFoundation

class ScannerViewController: UIViewController {

    var captureSession = AVCaptureSession()

    var videoPreviewLayer: AVCaptureVideoPreviewLayer?
    var qrCodeFrameView: UIView?

    var scannerMetadataObj : AVMetadataMachineReadableCodeObject?

    @IBOutlet weak var testImageView: UIImageView!


    override func viewDidLoad() {
        super.viewDidLoad()


        let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back)

        guard let captureDevice = deviceDiscoverySession.devices.first else {
            print("Failed to get the camera device")
            return
        }

        do {

            let input = try AVCaptureDeviceInput(device: captureDevice)

            captureSession.addInput(input)

            let captureMetadataOutput = AVCaptureMetadataOutput()
            captureSession.addOutput(captureMetadataOutput)

            captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
            captureMetadataOutput.metadataObjectTypes = supportedCodeTypes

        } catch {
            return
        }

        videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        videoPreviewLayer?.frame = view.layer.bounds
        view.layer.addSublayer(videoPreviewLayer!)

        qrCodeFrameView = UIView()

        if let qrCodeFrameView = qrCodeFrameView {
            qrCodeFrameView.layer.borderColor = UIColor.green.cgColor
            qrCodeFrameView.layer.borderWidth = 2
            view.addSubview(qrCodeFrameView)
            view.bringSubviewToFront(qrCodeFrameView)
        }


    }


    override func viewWillAppear(_ animated: Bool) {
        captureSession.startRunning()

    }

    override func viewWillDisappear(_ animated: Bool) {
        captureSession.stopRunning()
        qrCodeFrameView?.frame = CGRect.zero
    }

}


extension ScannerViewController: AVCaptureMetadataOutputObjectsDelegate {

    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        // Check if the metadataObjects array is not nil and it contains at least one object.
        if metadataObjects.count == 0 {
            qrCodeFrameView?.frame = CGRect.zero
            return
        }


        // Get the metadata object.
        let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject

        scannerMetadataObj = metadataObj

        let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
        qrCodeFrameView?.frame = barCodeObject!.bounds

        self.testImageView.image = // set image with qr-code
    }

}

扫描二维码后,我想获取二维码的图像并将testImageView的图像设置为获得的图像。怎么可能?我这样做是因为我想将该图像保存在数据库中以备将来使用。在这里,我唯一的问题是如何从videoPreviewLayer获取qr代码的图像并将testImageView的图像设置为该图像。

1 个答案:

答案 0 :(得分:0)

您可以在需要时添加AVCapturePhotoOutput和capturePhoto。

  1. 在ScannerViewController中添加两个属性:

    private let photoOutput = AVCapturePhotoOutput()
    private var isCapturing = false
    
  2. 在viewDidLoad处将新的输出添加到captureSession:

    captureSession.addOutput(photoOutput)
    
  3. 在metadataOutput方法上调用capturePhoto并记住捕获状态。因为metadataOutput方法可以经常调用:

    let photoSettings = AVCapturePhotoSettings()
    if !isCapturing {
        isCapturing = true
        photoOutput.capturePhoto(with: photoSettings, delegate: self)
    }
    
  4. 实施AVCapturePhotoCaptureDelegate协议:

    extension ScannerViewController: AVCapturePhotoCaptureDelegate {
        func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
            isCapturing = false
            guard let imageData = photo.fileDataRepresentation() else {
                print("Error while generating image from photo capture data.");
                return
            }
            guard let qrImage = UIImage(data: imageData) else {
                print("Unable to generate UIImage from image data.");
                return
            }
            testImageView.image = qrImage
         }
    }
    
  5. 如果需要,还可以进行一些其他照片设置和错误处理。