博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用系统自带的框架完成扫描二维码、条形码,以及识别相册中的二维码
阅读量:6375 次
发布时间:2019-06-23

本文共 5743 字,大约阅读时间需要 19 分钟。

hot3.png

一、生成二维码(使用coreImage.framework)

- (CIImage *)createQRForString:(NSString *)qrString {

    // Need to convert the string to a UTF-8 encoded NSData object
    NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];
    // Create the filter
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // Set the message content and error-correction level
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
    // Send the image back
    return qrFilter.outputImage;
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {

    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // create a bitmap image that we'll draw into a bitmap context at the desired size;
    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:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // Create an image with the contents of our bitmap
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    // Cleanup
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    
    return [self imageBlackToTransparent:[UIImage imageWithCGImage:scaledImage] withRed:20.0f andGreen:70.0f andBlue:60.0f];
}
void ProviderReleaseData (void *info, const void *data, size_t size){
    free((void*)data);
}

然后用一句话调用

    [self.imageview setImage:[self createNonInterpolatedUIImageFormCIImage:[self createQRForString:@"今天"] withSize:size]];

就可生成二维码。

二、扫描二维码、条形码(使用AVFoundation.framework)

1.导入#import <AVFoundation/AVFoundation.h>,遵循AVCaptureMetadataOutputObjectsDelegate协议

,并实现- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection这个方法。

2.声明

@property (strong,nonatomic)AVCaptureDevice * device;  //设备

@property (strong,nonatomic)AVCaptureDeviceInput * input; //输入流
@property (strong,nonatomic)AVCaptureMetadataOutput * output; //输出流
@property (strong,nonatomic)AVCaptureSession * session;//捕捉会话
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview; //预览图层

在viewDidLoad中实现

    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];

    _output = [[AVCaptureMetadataOutput alloc]init];

    [_output setRectOfInterest:CGRectMake((Height/3.0-10)/Height,0,(Height/3.0+20)/Height,1)];

    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

self.session = [[AVCaptureSession alloc]init];

    if ([_session canSetSessionPreset:AVCaptureSessionPreset1920x1080])
    {
        [_session setSessionPreset:AVCaptureSessionPreset1920x1080];
    }
    else if ([_session canSetSessionPreset:AVCaptureSessionPreset1280x720])
    {
        [_session setSessionPreset:AVCaptureSessionPreset1280x720];
    }
    else
    {
        [_session setSessionPreset:AVCaptureSessionPresetPhoto];
    }

 if ([_session canAddInput:self.input])

    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }

// 条码类型 AVMetadataObjectTypeQRCode

//    _output.metadataObjectTypes =@[AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code];

    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];

   
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =CGRectMake(0,0,Width,Height);
    [self.view.layer insertSublayer:self.preview atIndex:0];
   
    // 开启
    [_session startRunning];

在代理方法中实现下面代码

if ([metadataObjects count] >0)

    {

     //结束

        [_session stopRunning];
        //扫描到以后
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        NSLog(@"%@",metadataObject.stringValue);
        [self playBeep];//添加声音
        self.textlabel.text=[NSString stringWithFormat:@"扫描信息:%@",metadataObject.stringValue];
        
    }

使用此方法可以添加扫描到信息成功的声音

- (void)playBeep{

    SystemSoundID soundID;
    NSString *path = [NSString stringWithFormat:@"/System/Library/Audio/UISounds/%@.%@",@"lock",@"caf"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
    AudioServicesPlaySystemSound(soundID);
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

 

三、识别相册中的二维码(使用coreImage.framework)

1.不用导入文件,遵循UIImagePickerControllerDelegate,UINavigationControllerDelegate两个协议

2.打开相册

UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];

    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];

3.

//选中图片的回调

-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *content = @"" ;
    //取出选中的图片
    UIImage *pickImage = info[UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImagePNGRepresentation(pickImage);
    CIImage *ciImage = [CIImage imageWithData:imageData];
    
    //创建探测器
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
    NSArray *feature = [detector featuresInImage:ciImage];
    
    //取出探测到的数据
    for (CIQRCodeFeature *result in feature) {
        content = result.messageString;
    }
    NSLog(@"%@",content);
    [picker dismissViewControllerAnimated:YES completion:nil];
    //进行处理(音效、网址分析、页面跳转等)
      
}

 

 

 

 

 

 

转载于:https://my.oschina.net/u/2330410/blog/683890

你可能感兴趣的文章
Vizinex RFID 和Brady SmartID推出航空标签
查看>>
Facebook 否认趋势话题存在政治偏见,但将做出调整
查看>>
云纵发布“纵横客“ 新一代互联网CRM开启餐饮行业营销新模式
查看>>
物联网到底何时才能称为“爆发”?
查看>>
《Java多线程编程核心技术》——1.2节使用多线程
查看>>
不用惊慌 关于苹果警告的一些分析
查看>>
《VMware 网络技术:原理与实践》—— 2.3 OSI模型
查看>>
金融安全资讯精选 2017年第十五期:普华永道消费者隐私信息保护调研称69%的企业无力面对网络攻击,中小银行转型系统整合中的建议...
查看>>
读书笔记之《实战Java虚拟机》(9):Class 文件结构
查看>>
面对区块链这项全新的技术,传统投资产生了焦虑
查看>>
1024城市峰会 | 当A.I.邂逅古都西安
查看>>
好看的卡片阴影
查看>>
理解 Mach O 并提高程序启动速度
查看>>
Vue实战篇(PC端商城项目)
查看>>
每周记录(二)
查看>>
你要做的是产品经理,不是作图经理!
查看>>
编码、摘要和加密(一)——字节编码
查看>>
JavaEE 项目常见错误汇总
查看>>
快速掌握Python基础语法(下)
查看>>
java虚拟机——运行时数据区域
查看>>