gpt4 book ai didi

swift - 如何使用 Swift 扫描 UIImage 中的二维码

转载 作者:可可西里 更新时间:2023-11-01 02:16:16 25 4
gpt4 key购买 nike

我正在尝试使用 Swift 从静态图像中读取 QR 码。

我可以使用视频源轻松阅读它,尽管图像看起来非常不同,而且我在网上找不到太多资源。

感谢任何帮助,谢谢。

最佳答案

您可以使用 ZXingObjC 制作出色的 QRCode 扫描器.它是一个条形码图像处理库,设计用于 iOS 设备和 Mac 应用程序。它从实时视频或照片库中的图像进行扫描,并支持所有主要的 QRCode 格式。

这只是为了让您朝着正确的方向开始。您将需要更多方法来设置相机等。ZXingObjC 包含示例项目,并且整个 SO 都有相机设置解决方案,所以这非常简单。

当然,您需要安装 ZXingObjC pods pod 'ZXingObjC' 并创建一个 bridging-header.h 文件才能使用 ZXingObjC 库.

ViewController.swift

import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var labelOutput: UILabel!
@IBOutlet weak var QRImage: UIImageView!

var imagePicker = UIImagePickerController()

// imagePicker delegate is itself (UIImagePickerController)
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

@IBAction func scanQRCode(sender: AnyObject) {
imagePicker.sourceType = .PhotoLibrary
imagePicker.allowsEditing = false
presentViewController(imagePicker, animated: true, completion: nil)
}

// set up the picker
// initialize luminance source, scanning algorithm, decoding of bitmap, reader helpers, decoder
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

let placeHolderImage:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
QRImage.contentMode = .ScaleAspectFit
QRImage.image = placeHolderImage
dismissViewControllerAnimated(true, completion: nil)

let luminanceSource: ZXLuminanceSource = ZXCGImageLuminanceSource(CGImage: placeHolderImage.CGImage)
let binarizer = ZXHybridBinarizer(source: luminanceSource)
let bitmap = ZXBinaryBitmap(binarizer: binarizer)
let hints: ZXDecodeHints = ZXDecodeHints.hints() as! ZXDecodeHints
let QRReader = ZXMultiFormatReader()

// throw/do/catch and all that jazz
do {
let result = try QRReader.decode(bitmap, hints: hints)
labelOutput.text = result.text
} catch let err as NSError {
print(err)
}
}

// Conform to ZXCaptureDelegate
func captureResult(capture: ZXCapture!, result: ZXResult!) {
// do some stuff
return
}
}

One note: As of this post there is a known initializer error in the library's ZXParsedResult.m file. After installing the library the location of the file in Xcode is: Project -> Pods -> ZXingObjC -> All -> ZXParsedResult.m

第 29 行更改 Objective-C 代码

+ (id)parsedResultWithType:(ZXParsedResultType)type {
return [[self alloc] initWithType:type];
}

+ (id)parsedResultWithType:(ZXParsedResultType)type {
return [(ZXParsedResult *)[self alloc] initWithType:type];
}

关于swift - 如何使用 Swift 扫描 UIImage 中的二维码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38298488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com