本節實現效果:在圖片內嵌入文字實現驗證碼;
核心知識: 提取圖片指定區域主色調;
重要說明:代碼中所涉及的坐標均基于圖片實際像素尺寸坐標,并非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];