图文混合验证码实现


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


重要说明:代码中所涉及的坐标均基于图片实际像素尺寸坐标,并非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];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,062评论 25 707
  • HTML标签解释大全 一、HTML标记 标签:!DOCTYPE 说明:指定了 HTML 文档遵循的文档类型定义(D...
    米塔塔阅读 3,208评论 1 41
  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,705评论 1 92
  • 请把我的生命交给你吧 让你的唇吻过我的每一寸肌肤 让我醉死在你的温情里 请在清晨的霞光到来之际 给我带上你编织的花...
    耀坤Rosy阅读 428评论 0 6
  • 就在昨天,我吸到了我从小到大吸过的浓度最大的霾。我知道我还太年轻,没见过什么世面,自以为吸了口对广大群众来说超级普...
    懒惰的家伙阅读 476评论 0 0