我使用google api图表生成qr代码,在浏览器中点击api时在浏览器中生成图像,但是如何在图像中接收它。我尝试使用以下代码,但它没有成功。
+(UIImage *)generateQR:(NSDictionary *)data
{
NSString *urlStr = [NSString stringWithFormat:@"http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl=%@", [data valueForKey:@"data"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:
[urlStr stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding]]];
NSString *responseString = [MyEventApi sendRequest:request];
// NSLog(@"response:%@", responseString);
NSError *error;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
UIImage *imgData = [[UIImage alloc]initWithData:jsonData];
NSLog(@"dict in API-------------%@",imgData);
return imgData;
}
请指导以上。
提前致谢。
答案 0 :(得分:1)
您好这里有一个GitHub示例,您可以在应用中生成QRCODE并获取如下图像: -
请检查以下示例可能是它的帮助是你我的朋友
答案 1 :(得分:0)
使用如下:
img1.image = UIImage.createQRImage(str: "hello world")
img2.image = UIImage.createQRImage(str: "hello world", length: 100)
public extension UIImage {
/// 生成二维码图片
/// 图片放大会模糊
/// - Parameter str: 二维码内容
/// - Returns: image
class func createQRImage(str: String) -> UIImage {
let data = str.data(using: .utf8)
let filter = CIFilter(name: "CIQRCodeGenerator")!
filter.setValue(data, forKey: "inputMessage")
filter.setValue("H", forKey: "inputCorrectionLevel")
let outPut = filter.outputImage!
return UIImage(ciImage: outPut, scale: UIScreen.main.scale, orientation: .up)
}
/// 生成指定尺寸高清二维码图片
///
/// - Parameters:
/// - str:
/// - length: 图片边长
/// - Returns:
class func createQRImage(str: String, length: CGFloat) -> UIImage? {
guard let image = UIImage.createQRCIImage(str: str) else {
return nil
}
return UIImage.createNonInterpolatedImage(image: image, length: length)
}
class func createQRCIImage(str: String) -> CIImage? {
let data = str.data(using: .utf8)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue("H", forKey: "inputCorrectionLevel")
let outPut = filter?.outputImage
return outPut
}
class func createNonInterpolatedImage(image: CIImage?, length: CGFloat) -> UIImage? {
guard let image = image else { return nil }
let extent = image.extent.integral
let scale = min(length / extent.width, length / extent.height)
// 1. 创建bitmap
let w = extent.width * scale
let h = extent.height * scale
let cs = CGColorSpaceCreateDeviceGray()
let bitmapRef = CGContext(data: nil, width: Int(w), height: Int(h), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: CGImageAlphaInfo.none.rawValue)
let context = CIContext(options: nil)
if let bitmapImage = context.createCGImage(image, from: extent) {
bitmapRef?.interpolationQuality = .none
bitmapRef?.scaleBy(x: scale, y: scale)
bitmapRef?.draw(bitmapImage, in: extent)
} else {
return nil
}
// 2. 保存bitmap到图片
guard let scaledImage = bitmapRef?.makeImage() else {
return nil
}
return UIImage(cgImage: scaledImage)
}
}