CIImage+.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // CIImage+.swift
  3. // EFQRCode
  4. //
  5. // Created by EyreFree on 2017/3/29.
  6. //
  7. // Copyright (c) 2017 EyreFree <eyrefree@eyrefree.org>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if os(iOS) || os(tvOS) || os(macOS)
  27. import CoreImage
  28. public extension CIImage {
  29. /// Convert CIImage To CGImage
  30. /// http://wiki.hawkguide.com/wiki/Swift:_Convert_between_CGImage,_CIImage_and_UIImage
  31. func toCGImage() -> CGImage? {
  32. return CIContext().createCGImage(self, from: extent)
  33. }
  34. /// Size
  35. func size() -> CGSize {
  36. return extent.size
  37. }
  38. /// Get QRCode from image
  39. func recognizeQRCode(options: [String : Any]? = nil) -> [String] {
  40. var result = [String]()
  41. let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: options)
  42. guard let features = detector?.features(in: self) else {
  43. return result
  44. }
  45. result = features.compactMap { feature in
  46. (feature as? CIQRCodeFeature)?.messageString
  47. }
  48. return result
  49. }
  50. /// Create QR CIImage
  51. static func generateQRCode(string: String, inputCorrectionLevel: EFInputCorrectionLevel = .m) -> CIImage? {
  52. let stringData = string.data(using: .utf8)
  53. guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else {
  54. return nil
  55. }
  56. qrFilter.setValue(stringData, forKey: "inputMessage")
  57. qrFilter.setValue(["L", "M", "Q", "H"][inputCorrectionLevel.rawValue], forKey: "inputCorrectionLevel")
  58. return qrFilter.outputImage
  59. }
  60. }
  61. #endif