Swift - Image Data From CIImage QR Code / How to render CIFilter Output

后端 未结 1 1137
温柔的废话
温柔的废话 2020-12-06 21:04

I\'ve been having this problem for a while now and looked at dozens of answers here and can\'t seem to find anything that helps.

Scenario

I am generating a

1条回答
  •  不思量自难忘°
    2020-12-06 21:14

    You have a couple of issues in your code. You need to convert your string to data using String Encoding isoLatin1 before passing it to the filter. Another issue is that to convert your CIImage to data you need to redraw/render your CIImage and to prevent blurring the image when scaled you need to apply a transform to the image to increase its size:

    extension StringProtocol {
        var qrCode: UIImage? {
            guard
                let data = data(using: .isoLatin1),
                let outputImage = CIFilter(name: "CIQRCodeGenerator",
                                  parameters: ["inputMessage": data, "inputCorrectionLevel": "M"])?.outputImage
            else { return nil }
            let size = outputImage.extent.integral
            let output = CGSize(width: 250, height: 250)
            let format = UIGraphicsImageRendererFormat()
            format.scale = UIScreen.main.scale
            return UIGraphicsImageRenderer(size: output, format: format).image { _ in outputImage
                .transformed(by: .init(scaleX: output.width/size.width, y: output.height/size.height))
                .image
                .draw(in: .init(origin: .zero, size: output))
            }
        }
    }
    extension CIImage {
        var image: UIImage { .init(ciImage: self) }
    }
    

    Playground testing:

    let link = "https://stackoverflow.com/questions/51178573/swift-image-data-from-ciimage-qr-code-how-to-render-cifilter-output?noredirect=1"
    let image = link.qrCode!
    let data =  image.jpegData(compressionQuality: 1)  // 154785 bytes
    

    0 讨论(0)
提交回复
热议问题