Swift CoreImage 高斯模糊、二維碼及條形碼生成

濾鏡類 CIFilter

CIFilter是CoreImage中提供的圖像過濾器,也可以將其理解為濾鏡。許多美顏應(yīng)用,圖像處理應(yīng)用等都是為原圖添加了濾鏡效果。系統(tǒng)通過了很多的濾鏡效果, 分成多種類別,在CIFilter類中可以看到。


系統(tǒng)通過的過濾效果分類

系統(tǒng)提供了從指定分類中獲取各種濾鏡效果的方法:

獲取各種濾鏡的方法
// 嘗試打印模糊類別過濾器
print(CIFilter.filterNames(inCategory: kCICategoryBlur))

下面處理兩種較為常見的用法: 高斯模糊、二維碼及條形碼生成

1、高斯模糊 處理

func createGaussianBlurImage(_ image: UIImage) -> UIImage? {
    guard let ciImage = CIImage(image: image) else { return nil }
    // 創(chuàng)建高斯模糊濾鏡類
    guard let blurFilter = CIFilter(name: "CIGaussianBlur") else { return nil }
    
    // key 可以在控制臺打印 po blurFilter.inputKeys
    // 設(shè)置圖片
    blurFilter.setValue(ciImage, forKey: "inputImage")
    // 設(shè)置模糊值
    blurFilter.setValue(20, forKey: "inputRadius")
    // 從濾鏡中 取出圖片
    guard let outputImage = blurFilter.outputImage else { return nil }

    // 創(chuàng)建上下文
    let context = CIContext(options: nil)
    // 根據(jù)濾鏡中的圖片 創(chuàng)建CGImage
    guard let cgImage = context.createCGImage(outputImage, from: ciImage.extent) else { return nil }
    
    return UIImage(cgImage: cgImage)
}

2、二維碼生成 處理

包含給二維碼添加前景色、背景色、頭像操作


/// 生成二維碼
func generateQRCode(_ content: String, size: CGFloat, avatar: UIImage?, foregroundColor: UIColor = .black, backgroundColor: UIColor = .white) -> UIImage? {
    guard let generateFilter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
    // 設(shè)置二維碼內(nèi)容
    generateFilter.setValue(content.data(using: .utf8), forKey: "inputMessage")
    // 設(shè)置二維碼的級別(糾錯率) L: 7% M(默認(rèn)): 15% Q: 25% H: 30%
    generateFilter.setValue("H", forKeyPath: "inputCorrectionLevel")
    
    // 直接返回 UIImage(ciImage: outputImage) 會是模糊的二維碼
    guard let outputImage = generateFilter.outputImage else { return nil }

    // 轉(zhuǎn)化為 清晰的圖像
    guard let clearImage = generateNonInterpolatedQRCode(outputImage, size: size) else { return nil }
    
    // 設(shè)置二維碼 顏色
    guard let colorsImage = setQRCodeColors(clearImage, foregroundColor: foregroundColor, backgroundColor: backgroundColor) else { return nil}
    
    // 返回插入頭像的二維碼
    return insertAvatarToQRCode(avatar, qrCodeImage: colorsImage)
    
}

/// 生成清晰的 二維碼
func generateNonInterpolatedQRCode(_ ciImage: CIImage, size: CGFloat) -> UIImage? {
    // 調(diào)整圖片大小及位置(小數(shù)跳轉(zhuǎn)為整數(shù))位置值向下調(diào)整,大小只向上調(diào)整
    let extent = ciImage.extent.integral
    
    // 獲取圖片大小
    let scale = min(size / extent.width, size / extent.height)
    let outputImageWidth = extent.width * scale
    let outputImageHeight = extent.height * scale
    
    // 創(chuàng)建依賴于設(shè)備的灰度顏色通道
    let space = CGColorSpaceCreateDeviceGray()
    
    // 創(chuàng)建圖形上下文
    let bitmapContext = CGContext(data: nil, width: Int(outputImageWidth), height: Int(outputImageHeight), bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: 0)
    
    // 設(shè)置縮放
    bitmapContext?.scaleBy(x: scale, y: scale)
    // 設(shè)置上下文渲染等級
    bitmapContext?.interpolationQuality = .none
    
    // 上下文
    let context = CIContext(options: nil)
    // 創(chuàng)建 cgImage
    guard let cgImage = context.createCGImage(ciImage, from: extent) else { return nil }
        
    // 繪圖
    bitmapContext?.draw(cgImage, in: extent)
    
    // 從圖形上下文中創(chuàng)建圖片
    guard let scaledImage = bitmapContext?.makeImage() else { return nil }
    
    // 返回UIImage
    return UIImage(cgImage: scaledImage)
    
}

/// 設(shè)置二維碼前景色 和背景色
func setQRCodeColors(_ image: UIImage, foregroundColor: UIColor, backgroundColor: UIColor) -> UIImage? {

    guard let colorFilter = CIFilter(name: "CIFalseColor") else { return nil }
    let ciImage = CIImage(image: image)
    
    // 設(shè)置圖片
    colorFilter.setValue(ciImage, forKey: "inputImage")
    // 設(shè)置前景色
    colorFilter.setValue(CIColor(color: foregroundColor), forKey: "inputColor0")
    // 設(shè)置背景色
    colorFilter.setValue(CIColor(color: backgroundColor), forKey: "inputColor1")
    
    // 輸出圖片
    guard let outputImage = colorFilter.outputImage else { return nil }
    
    return UIImage(ciImage: outputImage)
}

/// 往 二維碼中 插入頭像
func insertAvatarToQRCode(_ avatar: UIImage?, qrCodeImage: UIImage) -> UIImage? {
    guard let avatarSize = avatar?.size else { return qrCodeImage }
    let qrCodeSize = qrCodeImage.size
    // 開啟上下文
    UIGraphicsBeginImageContext(qrCodeSize)
    
    // 設(shè)置頭像的最大值
    var maxAvatarSize = min(avatarSize.width, avatarSize.height)
    maxAvatarSize = min(qrCodeSize.width / 3, maxAvatarSize)
    
    // 繪制二維碼圖片
    qrCodeImage.draw(in: CGRect(origin: .zero, size: qrCodeSize))
    // 繪制頭像
    avatar?.draw(in: CGRect(x: (qrCodeSize.width - maxAvatarSize) / 2, y: (qrCodeSize.height - maxAvatarSize) / 2, width: maxAvatarSize, height: maxAvatarSize))
    // 獲取圖片
    let outputImage = UIGraphicsGetImageFromCurrentImageContext()
    // 關(guān)閉上下文
    UIGraphicsEndImageContext()
    return outputImage
}

3、條形碼生成

/// 生成條形碼
func generateBarcode(_ content: String, size: CGSize) -> UIImage? {
    guard let barcodeFilter = CIFilter(name: "CICode128BarcodeGenerator") else { return nil }
    // 條形碼內(nèi)容
    barcodeFilter.setValue(content.data(using: .utf8), forKey: "inputMessage")
    // 左右間距
    barcodeFilter.setValue(0, forKey: "inputQuietSpace")
    // 高度 -> "inputBarcodeHeight"
    
    guard let outputImage = barcodeFilter.outputImage else { return nil }
    
    // 調(diào)整圖片大小及位置(小數(shù)跳轉(zhuǎn)為整數(shù))位置值向下調(diào)整,大小只向上調(diào)整
    let extent = outputImage.extent.integral
    
    // 條形碼放大 處理模糊
    let scaleX = size.width / extent.width
    let scaleY = size.height / extent.height
    let clearImage = UIImage(ciImage: outputImage.transformed(by: CGAffineTransform(scaleX: scaleX, y: scaleY)))
    
    return clearImage
}

/// 往 條形碼中插入 文本
func insertTextToBarcode(_ text: String?, attributes: [NSAttributedString.Key: Any]?, height: CGFloat, barcodeImage: UIImage) -> UIImage? {
    guard let text = text else { return barcodeImage }
    let barcodeSize = barcodeImage.size
    
    // 開啟上下文
    UIGraphicsBeginImageContext(CGSize(width: barcodeSize.width, height: barcodeSize.height + 20))
    
    // 繪制條形碼圖片
    barcodeImage.draw(in: CGRect(origin: .zero, size: barcodeSize))
    
    // 文本樣式
    let style = NSMutableParagraphStyle()
    style.alignment = .center
    let defaultAttributes: [NSAttributedString.Key: Any] = [
        .font: UIFont.systemFont(ofSize: 15),
        .foregroundColor: UIColor.black,
        .kern: 2,
        .paragraphStyle: style
    ]
    let attributes = attributes ?? defaultAttributes
    
    // 繪制文本
    (text as NSString).draw(in: CGRect(x: 0, y: barcodeSize.height, width: barcodeSize.width, height: height), withAttributes: attributes)
    // 獲取圖片
    let outputImage = UIGraphicsGetImageFromCurrentImageContext()
    // 關(guān)閉上下文
    UIGraphicsEndImageContext()
    return outputImage
}

二維碼識別

//        CIDetectorTypeFace 臉部識別
//        CIDetectorTypeRectangle 矩形識別
//        CIDetectorTypeQRCode 二維碼識別
//        CIDetectorTypeText 文本識別
    
guard let image = resultImageView.image else { return }
guard let ciImage = CIImage(image: image) else { return }

// 識別二維碼
let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
let features = detector?.features(in: ciImage)
guard let feature = features?.first as? CIQRCodeFeature else { return }

print(feature.messageString)

參考自:
swift 二維碼的生成
iOS開發(fā)之CoreImage框架使用(上)
CGContext 和 CIContext
iOS swift語言生成條形碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容