LBXScanWrapper.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. //
  2. // LBXScanWrapper.swift
  3. // swiftScan
  4. //
  5. // Created by lbxia on 15/12/10.
  6. // Copyright © 2015年 xialibing. All rights reserved.
  7. //
  8. import UIKit
  9. import AVFoundation
  10. public struct LBXScanResult {
  11. //码内容
  12. public var strScanned: String? = ""
  13. //扫描图像
  14. public var imgScanned: UIImage?
  15. //码的类型
  16. public var strBarCodeType: String? = ""
  17. //码在图像中的位置
  18. public var arrayCorner: [AnyObject]?
  19. public init(str: String?, img: UIImage?, barCodeType: String?, corner: [AnyObject]?)
  20. {
  21. self.strScanned = str
  22. self.imgScanned = img
  23. self.strBarCodeType = barCodeType
  24. self.arrayCorner = corner
  25. }
  26. }
  27. open class LBXScanWrapper: NSObject, AVCaptureMetadataOutputObjectsDelegate {
  28. let device = AVCaptureDevice.default(for: AVMediaType.video)
  29. var input: AVCaptureDeviceInput?
  30. var output: AVCaptureMetadataOutput
  31. let session = AVCaptureSession()
  32. var previewLayer: AVCaptureVideoPreviewLayer?
  33. var stillImageOutput: AVCaptureStillImageOutput?
  34. var videoPreView: UIView?
  35. var scaleSize:CGFloat = 1
  36. //存储返回结果
  37. var arrayResult: [LBXScanResult] = [];
  38. //扫码结果返回block
  39. var successBlock: ([LBXScanResult]) -> Void
  40. //是否需要拍照
  41. var isNeedCaptureImage: Bool
  42. //当前扫码结果是否处理
  43. var isNeedScanResult: Bool = true
  44. /**
  45. 初始化设备
  46. - parameter videoPreView: 视频显示UIView
  47. - parameter objType: 识别码的类型,缺省值 QR二维码
  48. - parameter isCaptureImg: 识别后是否采集当前照片
  49. - parameter cropRect: 识别区域
  50. - parameter success: 返回识别信息
  51. - returns:
  52. */
  53. init(videoPreView: UIView, objType: [AVMetadataObject.ObjectType] = [(AVMetadataObject.ObjectType.qr as NSString) as AVMetadataObject.ObjectType], isCaptureImg: Bool, cropRect: CGRect = CGRect.zero, success: @escaping (([LBXScanResult]) -> Void))
  54. {
  55. self.videoPreView = videoPreView
  56. do {
  57. input = try AVCaptureDeviceInput(device: device!)
  58. }
  59. catch let error as NSError {
  60. print("AVCaptureDeviceInput(): \(error)")
  61. }
  62. successBlock = success
  63. // Output
  64. output = AVCaptureMetadataOutput()
  65. isNeedCaptureImage = isCaptureImg
  66. stillImageOutput = AVCaptureStillImageOutput();
  67. super.init()
  68. if device == nil || input == nil {
  69. return
  70. }
  71. if session.canAddInput(input!) {
  72. session.addInput(input!)
  73. }
  74. if session.canAddOutput(output) {
  75. session.addOutput(output)
  76. }
  77. if session.canAddOutput(stillImageOutput!) {
  78. session.addOutput(stillImageOutput!)
  79. }
  80. let outputSettings: Dictionary = [AVVideoCodecJPEG: AVVideoCodecKey]
  81. stillImageOutput?.outputSettings = outputSettings
  82. session.sessionPreset = AVCaptureSession.Preset.high
  83. //参数设置
  84. output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
  85. output.metadataObjectTypes = objType
  86. if !cropRect.equalTo(CGRect.zero)
  87. {
  88. //启动相机后,直接修改该参数无效
  89. output.rectOfInterest = cropRect
  90. }
  91. previewLayer = AVCaptureVideoPreviewLayer(session: session)
  92. previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
  93. var frame: CGRect = videoPreView.frame
  94. frame.origin = CGPoint.zero
  95. previewLayer?.frame = frame
  96. videoPreView.layer.insertSublayer(previewLayer!, at: 0)
  97. do {
  98. try input?.device.lockForConfiguration()
  99. if device?.isWhiteBalanceModeSupported(.autoWhiteBalance) == true {
  100. input?.device.whiteBalanceMode = .autoWhiteBalance
  101. }
  102. if (device!.isFocusPointOfInterestSupported && device!.isFocusModeSupported(AVCaptureDevice.FocusMode.continuousAutoFocus))
  103. {
  104. input?.device.focusMode = AVCaptureDevice.FocusMode.continuousAutoFocus
  105. }
  106. input?.device.unlockForConfiguration()
  107. } catch let error as NSError {
  108. print("device.lockForConfiguration(): \(error)")
  109. }
  110. }
  111. public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
  112. captureOutput(output, didOutputMetadataObjects: metadataObjects, from: connection)
  113. }
  114. func start()
  115. {
  116. if !session.isRunning
  117. {
  118. isNeedScanResult = true
  119. session.startRunning()
  120. }
  121. }
  122. func stop()
  123. {
  124. if session.isRunning
  125. {
  126. isNeedScanResult = false
  127. session.stopRunning()
  128. }
  129. }
  130. // func setVideoScale(scale: CGFloat) {
  131. // print("调整镜头................")
  132. // do {
  133. // try input?.device.lockForConfiguration()
  134. // let videoConnection = self.connectionWithMediaType(mediaType: .video, connections: self.stillImageOutput?.connections ?? [])
  135. // let maxScaleAndCropFactor = self.stillImageOutput?.connection(with: .video)?.videoMaxScaleAndCropFactor ?? 0 / 16
  136. // var newScale = scale
  137. // if newScale > maxScaleAndCropFactor {
  138. // newScale = maxScaleAndCropFactor
  139. // }
  140. // print("scale.....\(newScale)")
  141. // let videoFactor = videoConnection?.videoScaleAndCropFactor ?? 1
  142. // let zoom = newScale / videoFactor
  143. // videoConnection?.videoScaleAndCropFactor = newScale
  144. // input?.device.unlockForConfiguration()
  145. // print("zoom.......\(zoom)")
  146. // if let transform = self.videoPreView?.transform {
  147. // self.videoPreView?.transform = transform.scaledBy(x: zoom, y: zoom)
  148. // }
  149. //
  150. // } catch let error as NSError {
  151. // print("device.lockForConfiguration(): \(error)")
  152. // }
  153. // }
  154. //
  155. // func changeVideoScale(obj: AVMetadataMachineReadableCodeObject?) {
  156. // if let o = obj {
  157. // let arr = o.corners
  158. // if arr.count >= 3 {
  159. // let point = arr[1]
  160. // let point2 = arr[2]
  161. // let scale = 150 / (point2.x - point.x) //当二维码图片宽小于150,进行放大
  162. // print("scale.......\(scale)")
  163. // if scale > 1 {
  164. // for item in stride(from: 1, to: scale, by: 0.01) {
  165. // self.setVideoScale(scale: item)
  166. // }
  167. // }
  168. // }
  169. // }
  170. // }
  171. open func captureOutput(_ captureOutput: AVCaptureOutput, didOutputMetadataObjects metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
  172. if !isNeedScanResult
  173. {
  174. //上一帧处理中
  175. return
  176. }
  177. isNeedScanResult = false
  178. arrayResult.removeAll()
  179. // print(metadataObjects)
  180. // if metadataObjects.count < 1 {
  181. // if self.scaleSize == 1 {
  182. // self.scaleSize = 2
  183. // }else {
  184. // self.scaleSize = 1
  185. // }
  186. // self.setVideoScale(scale: self.scaleSize)
  187. // }
  188. //识别扫码类型
  189. for current in metadataObjects
  190. {
  191. if (current).isKind(of: AVMetadataMachineReadableCodeObject.self)
  192. {
  193. let code = current as! AVMetadataMachineReadableCodeObject
  194. //码类型
  195. let codeType = code.type
  196. // print("code type:%@",codeType)
  197. //码内容
  198. let codeContent = code.stringValue
  199. // print("code string:%@",codeContent)
  200. //4个字典,分别 左上角-右上角-右下角-左下角的 坐标百分百,可以使用这个比例抠出码的图像
  201. // let arrayRatio = code.corners
  202. arrayResult.append(LBXScanResult(str: codeContent, img: UIImage(), barCodeType: codeType.rawValue, corner: code.corners as [AnyObject]?))
  203. }
  204. }
  205. if arrayResult.count > 0
  206. {
  207. if isNeedCaptureImage
  208. {
  209. captureImage()
  210. }
  211. else
  212. {
  213. stop()
  214. successBlock(arrayResult)
  215. }
  216. }
  217. else
  218. {
  219. isNeedScanResult = true
  220. }
  221. }
  222. //MARK: ----拍照
  223. open func captureImage()
  224. {
  225. let stillImageConnection: AVCaptureConnection? = connectionWithMediaType(mediaType: AVMediaType.video as AVMediaType, connections: (stillImageOutput?.connections)! as [AnyObject])
  226. stillImageOutput?.captureStillImageAsynchronously(from: stillImageConnection!, completionHandler: { (imageDataSampleBuffer, error) -> Void in
  227. self.stop()
  228. if imageDataSampleBuffer != nil
  229. {
  230. let imageData: Data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer!)!
  231. let scanImg: UIImage? = UIImage(data: imageData)
  232. for idx in 0...self.arrayResult.count - 1
  233. {
  234. self.arrayResult[idx].imgScanned = scanImg
  235. }
  236. }
  237. self.successBlock(self.arrayResult)
  238. })
  239. }
  240. open func connectionWithMediaType(mediaType: AVMediaType, connections: [AnyObject]) -> AVCaptureConnection?
  241. {
  242. for connection: AnyObject in connections
  243. {
  244. let connectionTmp: AVCaptureConnection = connection as! AVCaptureConnection
  245. for port: Any in connectionTmp.inputPorts
  246. {
  247. if (port as AnyObject).isKind(of: AVCaptureInput.Port.self)
  248. {
  249. let portTmp: AVCaptureInput.Port = port as! AVCaptureInput.Port
  250. if portTmp.mediaType == mediaType
  251. {
  252. return connectionTmp
  253. }
  254. }
  255. }
  256. }
  257. return nil
  258. }
  259. //MARK:切换识别区域
  260. open func changeScanRect(cropRect: CGRect)
  261. {
  262. //待测试,不知道是否有效
  263. stop()
  264. output.rectOfInterest = cropRect
  265. start()
  266. }
  267. //MARK: 切换识别码的类型
  268. open func changeScanType(objType: [AVMetadataObject.ObjectType])
  269. {
  270. //待测试中途修改是否有效
  271. output.metadataObjectTypes = objType
  272. }
  273. open func isGetFlash() -> Bool
  274. {
  275. if (device != nil && device!.hasFlash && device!.hasTorch)
  276. {
  277. return true
  278. }
  279. return false
  280. }
  281. /**
  282. 打开或关闭闪关灯
  283. - parameter torch: true:打开闪关灯 false:关闭闪光灯
  284. */
  285. open func setTorch(torch: Bool)
  286. {
  287. if isGetFlash()
  288. {
  289. do
  290. {
  291. try input?.device.lockForConfiguration()
  292. input?.device.torchMode = torch ? AVCaptureDevice.TorchMode.on : AVCaptureDevice.TorchMode.off
  293. input?.device.unlockForConfiguration()
  294. }
  295. catch let error as NSError {
  296. print("device.lockForConfiguration(): \(error)")
  297. }
  298. }
  299. }
  300. /**
  301. ------闪光灯打开或关闭
  302. */
  303. open func changeTorch()
  304. {
  305. if isGetFlash()
  306. {
  307. do
  308. {
  309. try input?.device.lockForConfiguration()
  310. var torch = false
  311. if input?.device.torchMode == AVCaptureDevice.TorchMode.on
  312. {
  313. torch = false
  314. }
  315. else if input?.device.torchMode == AVCaptureDevice.TorchMode.off
  316. {
  317. torch = true
  318. }
  319. input?.device.torchMode = torch ? AVCaptureDevice.TorchMode.on : AVCaptureDevice.TorchMode.off
  320. input?.device.unlockForConfiguration()
  321. }
  322. catch let error as NSError {
  323. print("device.lockForConfiguration(): \(error)")
  324. }
  325. }
  326. }
  327. //MARK: ------获取系统默认支持的码的类型
  328. static func defaultMetaDataObjectTypes() -> [AVMetadataObject.ObjectType]
  329. {
  330. var types =
  331. [AVMetadataObject.ObjectType.qr,
  332. AVMetadataObject.ObjectType.upce,
  333. AVMetadataObject.ObjectType.code39,
  334. AVMetadataObject.ObjectType.code39Mod43,
  335. AVMetadataObject.ObjectType.ean13,
  336. AVMetadataObject.ObjectType.ean8,
  337. AVMetadataObject.ObjectType.code93,
  338. AVMetadataObject.ObjectType.code128,
  339. AVMetadataObject.ObjectType.pdf417,
  340. AVMetadataObject.ObjectType.aztec
  341. ]
  342. //if #available(iOS 8.0, *)
  343. types.append(AVMetadataObject.ObjectType.interleaved2of5)
  344. types.append(AVMetadataObject.ObjectType.itf14)
  345. types.append(AVMetadataObject.ObjectType.dataMatrix)
  346. return types as [AVMetadataObject.ObjectType]
  347. }
  348. static func isSysIos8Later() -> Bool
  349. {
  350. // return floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_8_0
  351. if #available(iOS 8, *) {
  352. return true;
  353. }
  354. return false
  355. }
  356. /**
  357. 识别二维码码图像
  358. - parameter image: 二维码图像
  359. - returns: 返回识别结果
  360. */
  361. static public func recognizeQRImage(image: UIImage) -> [LBXScanResult]
  362. {
  363. var returnResult: [LBXScanResult] = []
  364. if LBXScanWrapper.isSysIos8Later()
  365. {
  366. //if #available(iOS 8.0, *)
  367. let detector: CIDetector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])!
  368. let img = CIImage(cgImage: (image.cgImage)!)
  369. let features: [CIFeature]? = detector.features(in: img, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
  370. if(features != nil && (features?.count)! > 0)
  371. {
  372. let feature = features![0]
  373. if feature.isKind(of: CIQRCodeFeature.self)
  374. {
  375. let featureTmp: CIQRCodeFeature = feature as! CIQRCodeFeature
  376. let scanResult = featureTmp.messageString
  377. let result = LBXScanResult(str: scanResult, img: image, barCodeType: AVMetadataObject.ObjectType.qr.rawValue, corner: nil)
  378. returnResult.append(result)
  379. }
  380. }
  381. }
  382. return returnResult
  383. }
  384. //MARK: -- - 生成二维码,背景色及二维码颜色设置
  385. static public func createCode(codeType: String, codeString: String, size: CGSize, qrColor: UIColor, bkColor: UIColor) -> UIImage?
  386. {
  387. //if #available(iOS 8.0, *)
  388. let stringData = codeString.data(using: String.Encoding.utf8)
  389. //系统自带能生成的码
  390. // CIAztecCodeGenerator
  391. // CICode128BarcodeGenerator
  392. // CIPDF417BarcodeGenerator
  393. // CIQRCodeGenerator
  394. let qrFilter = CIFilter(name: codeType)
  395. qrFilter?.setValue(stringData, forKey: "inputMessage")
  396. qrFilter?.setValue("H", forKey: "inputCorrectionLevel")
  397. //上色
  398. let colorFilter = CIFilter(name: "CIFalseColor", parameters: ["inputImage": qrFilter!.outputImage!, "inputColor0": CIColor(cgColor: qrColor.cgColor), "inputColor1": CIColor(cgColor: bkColor.cgColor)])
  399. let qrImage = colorFilter!.outputImage!;
  400. //绘制
  401. let cgImage = CIContext().createCGImage(qrImage, from: qrImage.extent)!
  402. UIGraphicsBeginImageContext(size);
  403. let context = UIGraphicsGetCurrentContext()!;
  404. context.interpolationQuality = CGInterpolationQuality.none;
  405. context.scaleBy(x: 1.0, y: -1.0);
  406. context.draw(cgImage, in: context.boundingBoxOfClipPath)
  407. let codeImage = UIGraphicsGetImageFromCurrentImageContext();
  408. UIGraphicsEndImageContext();
  409. return codeImage
  410. }
  411. static public func createCode128(codeString: String, size: CGSize, qrColor: UIColor, bkColor: UIColor) -> UIImage?
  412. {
  413. let stringData = codeString.data(using: String.Encoding.utf8)
  414. //系统自带能生成的码
  415. // CIAztecCodeGenerator 二维码
  416. // CICode128BarcodeGenerator 条形码
  417. // CIPDF417BarcodeGenerator
  418. // CIQRCodeGenerator 二维码
  419. let qrFilter = CIFilter(name: "CICode128BarcodeGenerator")
  420. qrFilter?.setDefaults()
  421. qrFilter?.setValue(stringData, forKey: "inputMessage")
  422. let outputImage: CIImage? = qrFilter?.outputImage
  423. let context = CIContext()
  424. let cgImage = context.createCGImage(outputImage!, from: outputImage!.extent)
  425. let image = UIImage(cgImage: cgImage!, scale: 1.0, orientation: UIImage.Orientation.up)
  426. // Resize without interpolating
  427. let scaleRate: CGFloat = 20.0
  428. let resized = resizeImage(image: image, quality: CGInterpolationQuality.none, rate: scaleRate)
  429. return resized;
  430. }
  431. //MARK:根据扫描结果,获取图像中得二维码区域图像(如果相机拍摄角度故意很倾斜,获取的图像效果很差)
  432. static func getConcreteCodeImage(srcCodeImage: UIImage, codeResult: LBXScanResult) -> UIImage?
  433. {
  434. let rect: CGRect = getConcreteCodeRectFromImage(srcCodeImage: srcCodeImage, codeResult: codeResult)
  435. if rect.isEmpty
  436. {
  437. return nil
  438. }
  439. let img = imageByCroppingWithStyle(srcImg: srcCodeImage, rect: rect)
  440. if img != nil
  441. {
  442. let imgRotation = imageRotation(image: img!, orientation: UIImage.Orientation.right)
  443. return imgRotation
  444. }
  445. return nil
  446. }
  447. //根据二维码的区域截取二维码区域图像
  448. static public func getConcreteCodeImage(srcCodeImage: UIImage, rect: CGRect) -> UIImage?
  449. {
  450. if rect.isEmpty
  451. {
  452. return nil
  453. }
  454. let img = imageByCroppingWithStyle(srcImg: srcCodeImage, rect: rect)
  455. if img != nil
  456. {
  457. let imgRotation = imageRotation(image: img!, orientation: UIImage.Orientation.right)
  458. return imgRotation
  459. }
  460. return nil
  461. }
  462. //获取二维码的图像区域
  463. static public func getConcreteCodeRectFromImage(srcCodeImage: UIImage, codeResult: LBXScanResult) -> CGRect
  464. {
  465. if (codeResult.arrayCorner == nil || (codeResult.arrayCorner?.count)! < 4)
  466. {
  467. return CGRect.zero
  468. }
  469. let corner: [[String: Float]] = codeResult.arrayCorner as! [[String: Float]]
  470. let dicTopLeft = corner[0]
  471. let dicTopRight = corner[1]
  472. let dicBottomRight = corner[2]
  473. let dicBottomLeft = corner[3]
  474. let xLeftTopRatio: Float = dicTopLeft["X"]!
  475. let yLeftTopRatio: Float = dicTopLeft["Y"]!
  476. let xRightTopRatio: Float = dicTopRight["X"]!
  477. let yRightTopRatio: Float = dicTopRight["Y"]!
  478. let xBottomRightRatio: Float = dicBottomRight["X"]!
  479. let yBottomRightRatio: Float = dicBottomRight["Y"]!
  480. let xLeftBottomRatio: Float = dicBottomLeft["X"]!
  481. let yLeftBottomRatio: Float = dicBottomLeft["Y"]!
  482. //由于截图只能矩形,所以截图不规则四边形的最大外围
  483. let xMinLeft = CGFloat(min(xLeftTopRatio, xLeftBottomRatio))
  484. let xMaxRight = CGFloat(max(xRightTopRatio, xBottomRightRatio))
  485. let yMinTop = CGFloat(min(yLeftTopRatio, yRightTopRatio))
  486. let yMaxBottom = CGFloat (max(yLeftBottomRatio, yBottomRightRatio))
  487. let imgW = srcCodeImage.size.width
  488. let imgH = srcCodeImage.size.height
  489. //宽高反过来计算
  490. let rect = CGRect(x: xMinLeft * imgH, y: yMinTop * imgW, width: (xMaxRight - xMinLeft) * imgH, height: (yMaxBottom - yMinTop) * imgW)
  491. return rect
  492. }
  493. //MARK: ----图像处理
  494. /**
  495. @brief 图像中间加logo图片
  496. @param srcImg 原图像
  497. @param LogoImage logo图像
  498. @param logoSize logo图像尺寸
  499. @return 加Logo的图像
  500. */
  501. static public func addImageLogo(srcImg: UIImage, logoImg: UIImage, logoSize: CGSize) -> UIImage
  502. {
  503. UIGraphicsBeginImageContext(srcImg.size);
  504. srcImg.draw(in: CGRect(x: 0, y: 0, width: srcImg.size.width, height: srcImg.size.height))
  505. let rect = CGRect(x: srcImg.size.width / 2 - logoSize.width / 2, y: srcImg.size.height / 2 - logoSize.height / 2, width: logoSize.width, height: logoSize.height);
  506. logoImg.draw(in: rect)
  507. let resultingImage = UIGraphicsGetImageFromCurrentImageContext();
  508. UIGraphicsEndImageContext();
  509. return resultingImage!;
  510. }
  511. //图像缩放
  512. static func resizeImage(image: UIImage, quality: CGInterpolationQuality, rate: CGFloat) -> UIImage?
  513. {
  514. var resized: UIImage?;
  515. let width = image.size.width * rate;
  516. let height = image.size.height * rate;
  517. UIGraphicsBeginImageContext(CGSize(width: width, height: height));
  518. let context = UIGraphicsGetCurrentContext();
  519. context!.interpolationQuality = quality;
  520. image.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
  521. resized = UIGraphicsGetImageFromCurrentImageContext();
  522. UIGraphicsEndImageContext();
  523. return resized;
  524. }
  525. //图像裁剪
  526. static func imageByCroppingWithStyle(srcImg: UIImage, rect: CGRect) -> UIImage?
  527. {
  528. let imageRef = srcImg.cgImage
  529. let imagePartRef = imageRef!.cropping(to: rect)
  530. let cropImage = UIImage(cgImage: imagePartRef!)
  531. return cropImage
  532. }
  533. //图像旋转
  534. static func imageRotation(image: UIImage, orientation: UIImage.Orientation) -> UIImage
  535. {
  536. var rotate: Double = 0.0;
  537. var rect: CGRect;
  538. var translateX: CGFloat = 0.0;
  539. var translateY: CGFloat = 0.0;
  540. var scaleX: CGFloat = 1.0;
  541. var scaleY: CGFloat = 1.0;
  542. switch (orientation) {
  543. case UIImage.Orientation.left:
  544. rotate = .pi / 2;
  545. rect = CGRect(x: 0, y: 0, width: image.size.height, height: image.size.width);
  546. translateX = 0;
  547. translateY = -rect.size.width;
  548. scaleY = rect.size.width / rect.size.height;
  549. scaleX = rect.size.height / rect.size.width;
  550. break;
  551. case UIImage.Orientation.right:
  552. rotate = 3 * .pi / 2;
  553. rect = CGRect(x: 0, y: 0, width: image.size.height, height: image.size.width);
  554. translateX = -rect.size.height;
  555. translateY = 0;
  556. scaleY = rect.size.width / rect.size.height;
  557. scaleX = rect.size.height / rect.size.width;
  558. break;
  559. case UIImage.Orientation.down:
  560. rotate = .pi;
  561. rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height);
  562. translateX = -rect.size.width;
  563. translateY = -rect.size.height;
  564. break;
  565. default:
  566. rotate = 0.0;
  567. rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height);
  568. translateX = 0;
  569. translateY = 0;
  570. break;
  571. }
  572. UIGraphicsBeginImageContext(rect.size);
  573. let context = UIGraphicsGetCurrentContext()!;
  574. //做CTM变换
  575. context.translateBy(x: 0.0, y: rect.size.height);
  576. context.scaleBy(x: 1.0, y: -1.0);
  577. context.rotate(by: CGFloat(rotate));
  578. context.translateBy(x: translateX, y: translateY);
  579. context.scaleBy(x: scaleX, y: scaleY);
  580. //绘制图片
  581. context.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height))
  582. let newPic = UIGraphicsGetImageFromCurrentImageContext();
  583. return newPic!;
  584. }
  585. deinit
  586. {
  587. // print("LBXScanWrapper deinit")
  588. }
  589. }