图文混合验证码实现

2018-02-07  本文已影响450人  hehtao

本节实现效果:在图片内嵌入文字实现验证码;
核心知识: 提取图片指定区域主色调;


重要说明:代码中所涉及的坐标均基于图片实际像素尺寸坐标,并非UIImageView的尺寸坐标;

实现步骤:
1.获取图片指定区域主要色彩;
2.在图片指定位置绘制文字做旋转.模糊.变形等处理;

一.效果如下:


图一:图片色调跳跃较大的情况 图二:图片色调较平滑的情况 图三:图片色调平滑的情况

可以明显的看出:
1.在图一的中文字过于明显,容易被提取特征点后分析识别;
2.在图二中局部区域比较理想,对于较明亮处依然存在图一的问题;
3.在图三中整体效果尚且可以,但是文字太暗,用户体验较差;
针对以上问题,其实都是图片本身过于明亮所致,故在重新绘制图片是选择- (void)drawInRect:(CGRect)rect blendMode:(CGBlendMode)blendMode alpha:(CGFloat)alpha方法,手动调节图片透明度即可,甚至可以给图片覆盖特定的前景色;
当然,既然获取了文字所在区域的像素值,人为制造噪点也是可以的!!!

二.获取图片指定区域主要色彩


主要代码如下:

-(UIColor*)mostColor:(UIImage*)image atRegion:(CGRect)region{
    
    CGImageRef inImage = image.CGImage;
    // Create off screen bitmap context to draw the image into. Format ARGB is 4 bytes for each pixel: Alpa, Red, Green, Blue
    CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];//该方法下文会讲解
    if (cgctx == NULL) {
        return nil; /* error */
    }
    
    size_t w = CGImageGetWidth(inImage);
    size_t h = CGImageGetHeight(inImage);
    CGRect rect = {{0,0},{w,h}};
    
    // 绘制
    CGContextDrawImage(cgctx, rect, inImage);
    
    // Now we can get a pointer to the image data associated with the bitmap
    // 对应像素点从左向右 Z 字型保存,所在在获取特定点时  offset = (w*y)+x
    unsigned char* data = (unsigned char*)CGBitmapContextGetData(cgctx);
     NSCountedSet *cls=[NSCountedSet setWithCapacity:region.size.width*region.size.height];
    
    // 获取坐标 x,y 处的像素点颜色值 ARGB
    for (NSInteger x = region.origin.x ; x<region.origin.x + region.size.width ; x++) {
        for (NSInteger y = region.origin.y; y< region.origin.y + region.size.height; y++) {
            
            NSInteger offset = 4*((w*y)+x);  //对应像素点从左向右 Z 字型保存
            if (offset + 4 >= w*h*4) {
                break;
            }
            NSInteger alpha = data[offset];
            NSInteger red   = data[offset + 1] ;
            NSInteger green = data[offset+2];
            NSInteger blue  = data[offset+3];
            
            [cls addObject:@[@(red),@(green),@(blue),@(alpha)]];
        }
    }
    
    CGContextRelease(cgctx);
    if (data) { free(data); }
    
    // 找到出现次数最多的那个颜色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
    NSArray *MaxColor = nil;
    NSUInteger MaxCount=0;
    
    while ( (curColor = [enumerator nextObject])){
        NSUInteger tmpCount = [cls countForObject:curColor];
        if ( tmpCount < MaxCount ) continue;
        MaxCount = tmpCount;
        MaxColor = curColor;
    }
    
    return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:1.f/*([MaxColor[3] intValue]/255.0f)*/];
}

上述代码没什么特别的地方,提一句NSCountedSet, NSCountedSet继承自NSSet,意味着NSCountedSet也不能存储相同的元素,但是,这个但是很及时,当NSCountedSet添加相同的元素时,会维护一个计数器,记录当前元素添加的次数,随后可以调用 countForObject获取对应元素存储次数;

CGImageRef 到 CGContextRef转换:

- (CGContextRef) createARGBBitmapContextFromImage:(CGImageRef) inImage {
    
    CGContextRef    context = NULL;
    CGColorSpaceRef colorSpace;
    void *          bitmapData;
    long             bitmapByteCount;
    long             bitmapBytesPerRow;
    
    // Get image width, height. We'll use the entire image.
    size_t pixelsWide = CGImageGetWidth(inImage);
    size_t pixelsHigh = CGImageGetHeight(inImage);
    
    // Declare the number of bytes per row. Each pixel in the bitmap in this
    // example is represented by 4 bytes; 8 bits each of red, green, blue, and
    // alpha.
    bitmapBytesPerRow   = (pixelsWide * 4);
    bitmapByteCount     = (bitmapBytesPerRow * pixelsHigh);
    
    // Use the generic RGB color space.
    colorSpace = CGColorSpaceCreateDeviceRGB();
    
    if (colorSpace == NULL){
        fprintf(stderr, "Error allocating color space\n");
        return NULL;
    }
    
    // Allocate memory for image data. This is the destination in memory
    // where any drawing to the bitmap context will be rendered.
    bitmapData = malloc( bitmapByteCount );
    if (bitmapData == NULL){
        fprintf (stderr, "Memory not allocated!");
        CGColorSpaceRelease( colorSpace );
        return NULL;
    }
    
    // Create the bitmap context. We want pre-multiplied ARGB, 8-bits
    // per component. Regardless of what the source image format is
    // (CMYK, Grayscale, and so on) it will be converted over to the format
    // specified here by CGBitmapContextCreate.
    context = CGBitmapContextCreate (bitmapData,
                                     pixelsWide,
                                     pixelsHigh,
                                     8,      // bits per component
                                     bitmapBytesPerRow,
                                     colorSpace,
                                     kCGImageAlphaPremultipliedFirst);
    if (context == NULL){
        free (bitmapData);
        fprintf (stderr, "Context not created!");
    }
    
    // Make sure and release colorspace before returning
    CGColorSpaceRelease( colorSpace );
    
    return context;
}

三.在图片指定位置绘制文字做旋转.模糊.变形等处理

-(UIImage *)drawTitles:(NSArray<NSString *> *)titles regions:(NSArray<NSString *> *)rects onImage:(UIImage *)sourceImage{
    //原始image的宽高
    CGFloat viewWidth = sourceImage.size.width;
    CGFloat viewHeight = sourceImage.size.height;
    //为了防止图片失真,绘制区域宽高和原始图片宽高一样
    UIGraphicsBeginImageContext(CGSizeMake(viewWidth, viewHeight));
//    [[UIColor lightGrayColor] setFill];
//    UIRectFill(CGRectMake(0, 0, viewWidth, viewHeight));
    //先将原始image绘制上
    [sourceImage drawInRect:CGRectMake(0, 0, viewWidth, viewHeight) blendMode:kCGBlendModeOverlay alpha:0.9f];
//    [sourceImage drawInRect:CGRectMake(0, 0, viewWidth, viewHeight)];
    //旋转上下文矩阵,绘制文字
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    for (int i = 0; i < titles.count; i++) {
        NSString *title = titles[i];
        // 文字所在位置
        CGRect region = CGRectFromString(rects[i]);
        // 主色调
        UIColor *mostColor = [self mostColor:sourceImage atRegion:region];
        // 随机旋转角
        CGFloat ratation = (M_PI / (rand() % 10 ));
    
        // 不建议随机处理阴影,避免大概率出现文字无法显示问题
        NSShadow *shadow = [[NSShadow alloc] init];
        shadow.shadowBlurRadius = 5;
        shadow.shadowColor = mostColor;
        shadow.shadowOffset = CGSizeMake(3  ,4);
        
        // 添加文本颜色和阴影等效果
        NSDictionary *attr = @{
                               //设置字体大小,可自行随机
                               NSFontAttributeName: [UIFont systemFontOfSize:100],
                               //设置文字颜色
                               NSForegroundColorAttributeName :mostColor,
                               NSShadowAttributeName:shadow,
                               NSVerticalGlyphFormAttributeName:@(0),
                               };
       
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:title attributes:attr];
        //将绘制原点(0,0)调整到源文字的中心
        CGContextConcatCTM(context, CGAffineTransformMakeTranslation(region.origin.x + region.size.width / 2.f, region.origin.y + region.size.height / 2.f));
        // 以源文字的中心为中心旋转
        CGContextConcatCTM(context, CGAffineTransformMakeRotation(ratation));
        // 将绘制原点恢复初始值,保证当前context中心和源image的中心处在一个点(当前context已经旋转,所以绘制出的任何layer都是倾斜的)
        CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-region.origin.x - region.size.width / 2.f, -region.origin.y -region.size.height / 2.f));
        // 绘制源文字
        [title drawInRect:CGRectMake(region.origin.x , region.origin.y, attrStr.size.width, attrStr.size.height) withAttributes:attr];
    }
    UIImage *finalImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGContextRestoreGState(context);
    return finalImg;
}

注释已经很详细了,不做赘述,直接看一个例子:

特别注意:
1.- (void)drawInRect:(CGRect)rect blendMode:(CGBlendMode)blendMode alpha:(CGFloat)alpha方法;
2.所有坐标均是基于图片本身像素尺寸,并非UIIMageView;

本例中所用图片 image.size 为:800*800,
注意需要保证rectN 的x+width < image.size.width 并且 y+height < image.size. height才可正确绘制,实际可根据自身情况对rectN采用合适的方式随机生成;

    // 按照图片尺寸随机即可
    NSString *rect1 = NSStringFromCGRect(CGRectMake(100, 350, 100, 100));
    NSString *rect2 = NSStringFromCGRect(CGRectMake(200, 400, 100, 100));
    NSString *rect3 = NSStringFromCGRect(CGRectMake(350, 200, 100, 100));
    NSString *rect4 = NSStringFromCGRect(CGRectMake(550, 300, 100, 100));
    
    self.filterImageView.image = [self drawTitles:@[@"测",@"试",@"字",@"体"]
                                          regions:@[rect1,rect2,rect3,rect4]
                                          onImage:self.originalImageView.image];
上一篇 下一篇

猜你喜欢

热点阅读