liufan321 / swiftqrcode Goto Github PK
View Code? Open in Web Editor NEWSimple QRCode detector and generator in Swift
License: MIT License
Simple QRCode detector and generator in Swift
License: MIT License
Hi any updates to the latest version of Swift?
UIImagePNGRepresentation always return nil
by the way:
qrImageView.image = QRCode.generateImage(Token.base64EncodedString(), avatarImage:nil)
if let qrImage = qrImageView.image {
let vc = UIActivityViewController(activityItems: [qrImage] as [Any], applicationActivities: [])
self.present(vc, animated: true, completion: nil)
}
I cant share the QRCode
please add swift 3 support
Can't figure out if there is a method to use the front camera instead of the back. This is my first post to GitHub issues. My apologies if my question is inappropriate here.
Is there a way to detect a QR code from an uploaded image?
Hi,
I'm trying to convert the generated qrcode image to data to send an mail attachment , but it always returns nil. Here follows sample code,
var qrCode = UIImage()
qrCode = QRCode.generateImage("123456", avatarImage: UIImage(named: ""), avatarScale: 0.3)!
let imgData = UIImageJPEGRepresentation(qrCode, 1.0)!
Hello, i have a problem. When i open viewController with qrReader it works very good.
But, when i open normal camera to take a photo, the qrReader do override all camera components, button take photo, preview image etc. How can i reset the camera objects ?
Ps: it happen after open qrReader. When i open normal camera before open qrReader, it works fine.
The condition to check if the session is running or not inside stopScan method is as follows:
if !session.running {
print("the capture session is running")
return
}
Instead it should be
if session.running {
print("the capture session is running")
return
}
The only change is to remove ! before session.running in the if condition.
In the branch of Swift 2.0
's demo,
When rotate the screen, the camera view will not fill the screen, and the direction won't change correspondingly.
在Swift2.0
分支的demo中,
当旋转屏幕时,相机视图不会填满屏幕,同时显示的方向也没有对应地改变。
在使用的时候发现没有调用相机扫描二维码的示例,希望刀哥完善下Demo...
扫描结果是代理吗?没找到怎么拿扫描结果呀?
Hi
Thank you for your nice library.
I have some trouble to stop scanning after detect the barcode string. How could I stop scan and pass the value (in fact where instead of how)?
Hi
Not Working in Swift 4.
`//
// QRCode.swift
// QRCode
//
// Created by 刘凡 on 15/5/15.
// Copyright (c) 2015年 joyios. All rights reserved.
//
import UIKit
import AVFoundation
open class QRCode: NSObject, AVCaptureMetadataOutputObjectsDelegate {
/// corner line width
var lineWidth: CGFloat
/// corner stroke color
var strokeColor: UIColor
/// the max count for detection
var maxDetectedCount: Int
/// current count for detection
var currentDetectedCount: Int = 0
/// auto remove sub layers when detection completed
var autoRemoveSubLayers: Bool
/// completion call back
var completedCallBack: ((_ stringValue: String) -> ())?
/// the scan rect, default is the bounds of the scan view, can modify it if need
open var scanFrame: CGRect = CGRect.zero
/// init function
///
/// - returns: the scanner object
public override init() {
self.lineWidth = 4
self.strokeColor = UIColor.green
self.maxDetectedCount = 20
self.autoRemoveSubLayers = false
super.init()
}
/// init function
///
/// - parameter autoRemoveSubLayers: remove sub layers auto after detected code image
/// - parameter lineWidth: line width, default is 4
/// - parameter strokeColor: stroke color, default is Green
/// - parameter maxDetectedCount: max detecte count, default is 20
///
/// - returns: the scanner object
public init(autoRemoveSubLayers: Bool, lineWidth: CGFloat = 4, strokeColor: UIColor = UIColor.green, maxDetectedCount: Int = 20) {
self.lineWidth = lineWidth
self.strokeColor = strokeColor
self.maxDetectedCount = maxDetectedCount
self.autoRemoveSubLayers = autoRemoveSubLayers
}
deinit {
if session.isRunning {
session.stopRunning()
}
removeAllLayers()
}
// MARK: - Generate QRCode Image
/// generate image
///
/// - parameter stringValue: string value to encoe
/// - parameter avatarImage: avatar image will display in the center of qrcode image
/// - parameter avatarScale: the scale for avatar image, default is 0.25
///
/// - returns: the generated image
class open func generateImage(_ stringValue: String, avatarImage: UIImage?, avatarScale: CGFloat = 0.25) -> UIImage? {
return generateImage(stringValue, avatarImage: avatarImage, avatarScale: avatarScale, color: CIColor(color: UIColor.black), backColor: CIColor(color: UIColor.white))
}
/// Generate Qrcode Image
///
/// - parameter stringValue: string value to encoe
/// - parameter avatarImage: avatar image will display in the center of qrcode image
/// - parameter avatarScale: the scale for avatar image, default is 0.25
/// - parameter color: the CI color for forenground, default is black
/// - parameter backColor: th CI color for background, default is white
///
/// - returns: the generated image
class open func generateImage(_ stringValue: String, avatarImage: UIImage?, avatarScale: CGFloat = 0.25, color: CIColor, backColor: CIColor) -> UIImage? {
// generate qrcode image
let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
qrFilter.setDefaults()
qrFilter.setValue(stringValue.data(using: String.Encoding.utf8, allowLossyConversion: false), forKey: "inputMessage")
let ciImage = qrFilter.outputImage
// scale qrcode image
let colorFilter = CIFilter(name: "CIFalseColor")!
colorFilter.setDefaults()
colorFilter.setValue(ciImage, forKey: "inputImage")
colorFilter.setValue(color, forKey: "inputColor0")
colorFilter.setValue(backColor, forKey: "inputColor1")
let transform = CGAffineTransform(scaleX: 10, y: 10)
let transformedImage = qrFilter.outputImage!.transformed(by: transform)
let image = UIImage(ciImage: transformedImage)
if avatarImage != nil {
return insertAvatarImage(image, avatarImage: avatarImage!, scale: avatarScale)
}
return image
}
class func insertAvatarImage(_ codeImage: UIImage, avatarImage: UIImage, scale: CGFloat) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: codeImage.size.width, height: codeImage.size.height)
UIGraphicsBeginImageContext(rect.size)
codeImage.draw(in: rect)
let avatarSize = CGSize(width: rect.size.width * scale, height: rect.size.height * scale)
let x = (rect.width - avatarSize.width) * 0.5
let y = (rect.height - avatarSize.height) * 0.5
avatarImage.draw(in: CGRect(x: x, y: y, width: avatarSize.width, height: avatarSize.height))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!
}
// MARK: - Video Scan
/// prepare scan
///
/// - parameter view: the scan view, the preview layer and the drawing layer will be insert into this view
/// - parameter completion: the completion call back
open func prepareScan(_ view: UIView, completion:@escaping (_ stringValue: String)->()) {
scanFrame = view.bounds
completedCallBack = completion
currentDetectedCount = 0
setupSession()
setupLayers(view)
}
/// start scan
open func startScan() {
if session.isRunning {
print("the capture session is running")
return
}
session.startRunning()
}
/// stop scan
open func stopScan() {
if !session.isRunning {
print("the capture session is not running")
return
}
session.stopRunning()
}
func setupLayers(_ view: UIView) {
drawLayer.frame = view.bounds
view.layer.insertSublayer(drawLayer, at: 0)
previewLayer.frame = view.bounds
view.layer.insertSublayer(previewLayer, at: 0)
}
func setupSession() {
if session.isRunning {
print("the capture session is running")
return
}
if !session.canAddInput(videoInput!) {
print("can not add input device")
return
}
if !session.canAddOutput(dataOutput) {
print("can not add output device")
return
}
session.addInput(videoInput!)
session.addOutput(dataOutput)
dataOutput.metadataObjectTypes = dataOutput.availableMetadataObjectTypes;
dataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
}
open func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
clearDrawLayer()
for dataObject in metadataObjects {
if let codeObject = dataObject as? AVMetadataMachineReadableCodeObject,
let obj = previewLayer.transformedMetadataObject(for: codeObject) as? AVMetadataMachineReadableCodeObject {
if scanFrame.contains(obj.bounds) {
currentDetectedCount = currentDetectedCount + 1
if currentDetectedCount > maxDetectedCount {
session.stopRunning()
completedCallBack!(codeObject.stringValue!)
if autoRemoveSubLayers {
removeAllLayers()
}
}
// transform codeObject
drawCodeCorners(previewLayer.transformedMetadataObject(for: codeObject) as! AVMetadataMachineReadableCodeObject)
}
}
}
}
open func removeAllLayers() {
previewLayer.removeFromSuperlayer()
drawLayer.removeFromSuperlayer()
}
func clearDrawLayer() {
if drawLayer.sublayers == nil {
return
}
for layer in drawLayer.sublayers! {
layer.removeFromSuperlayer()
}
}
func drawCodeCorners(_ codeObject: AVMetadataMachineReadableCodeObject) {
if codeObject.corners.count == 0 {
return
}
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = lineWidth
shapeLayer.strokeColor = strokeColor.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.path = createPath(codeObject.corners as NSArray).cgPath
drawLayer.addSublayer(shapeLayer)
}
func createPath(_ points: NSArray) -> UIBezierPath {
let path = UIBezierPath()
var point = CGPoint(dictionaryRepresentation: points[0] as! CFDictionary)
path.move(to: point!)
var index = 1
while index < points.count {
point = CGPoint(dictionaryRepresentation: points[index] as! CFDictionary)
path.addLine(to: point!)
index = index + 1
}
path.close()
return path
}
/// previewLayer
lazy var previewLayer: AVCaptureVideoPreviewLayer = {
let layer = AVCaptureVideoPreviewLayer(session: self.session)
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
return layer
}()
/// drawLayer
lazy var drawLayer = CALayer()
/// session
lazy var session = AVCaptureSession()
/// input
lazy var videoInput: AVCaptureDeviceInput? = {
if let device = AVCaptureDevice.default(for: .video) {
return try? AVCaptureDeviceInput(device: device)
}
return nil
}()
/// output
lazy var dataOutput = AVCaptureMetadataOutput()
}
`
I have change syntax error for Swift 4. But Its Not Working. Please Help me
xcode7.0编译不能通过,更改了很多
Hi there
First of all thank you for the framework. Do you plan to update it to Swift 4? I see open PRs concerning Swift 4 migration. Any chance for them to be merged?
When a screen is in landscape mode, the scanner camera seems in portrait mode. Any idea how the this can be fixed
Hi,
There's a small bug in generateImage() function that setting colors doesn't work.
let transformedImage = qrFilter.outputImage!.imageByApplyingTransform(transform)
If we change qrFilter to colorFilter, then the color change will work.
Thank you for writing this module!
Jenny
选择图片识别的功能是不是没有?
It seems that the version should be 1.0.1.
I notice there is a tag named 1.0.1.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.