iOS-字符串生成二维码或条形码

如今我们需要根据字符串或url来生成一个二维码或条形码图片。

1.生成二维码图片

-(void)loadQRCodeImg{
    //1.将字符串转出NSData
    NSData *img_data = [self.QRCode dataUsingEncoding:NSUTF8StringEncoding];
    
    //2.将字符串变成二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //  条形码 filter = [CIFilter filterWithName:@"CICode128BarcodeGenerator"];
    
    //3.恢复滤镜的默认属性
    [filter setDefaults];
    
    //4.设置滤镜的 inputMessage
    [filter setValue:img_data forKey:@"inputMessage"];
    
    //5.获得滤镜输出的图像
    CIImage *img_CIImage = [filter outputImage];
    
    //6.此时获得的二维码图片比较模糊,通过下面函数转换成高清
    self.img_QRCode = [self changeImageSizeWithCIImage:img_CIImage andSize:180];
}

 2.拉伸二维码图片

这种方法只适用于正方形的二维码,不适用条形码。

////拉伸二维码图片,使其清晰
- (UIImage *)changeImageSizeWithCIImage:(CIImage *)ciImage andSize:(CGFloat)size{
    CGRect extent = CGRectIntegral(ciImage.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:ciImage fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
}

3.拉伸条形码图片

我们可以将1.生成二维码图片中的第6点改成:

CGFloat scaleX = 300 / img_CIImage.extent.size.width;//300是你想要的长
CGFloat scaleY = 70 / img_CIImage.extent.size.height;//70是你想要的宽
img_CIImage = [img_CIImage imageByApplyingTransform:CGAffineTransformScale(CGAffineTransformIdentity, scaleX, scaleY)];
    
self.img_BarCode = [UIImage imageWithCIImage:img_CIImage];

 

你可能感兴趣的:(iOS-其他)