iOS 关于UIImage的处理总结

来源:互联网 发布:云网络 编辑:程序博客网 时间:2024/05/29 19:24
void ProviderReleaseData (void *info, const void *data, size_t size){    free((void*)data);}
#pragma mark - 去掉最常见颜色为透明颜色
- (UIImage*)imageBlackToTransparent:(UIImage*)image weight:(NSInteger)weight{    // 分配内存    const int imageWidth = image.size.width;        const int imageHeight = image.size.height;        size_t      bytesPerRow = imageWidth * 4;        uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);        // 创建context        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();        CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,                                                                                                  kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);        CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);        // 遍历像素    int pixelNum = imageWidth * imageHeight;        uint32_t* pCurPtr = rgbImageBuf;        NSDictionary *dictColor = [self mostColorFromImage:image];    CGFloat mostR = [dictColor[@"red"] floatValue];    CGFloat mostG = [dictColor[@"green"] floatValue];    CGFloat mostB = [dictColor[@"blue"] floatValue];        for (int i = 0; i < pixelNum; i++, pCurPtr++){        CGFloat r = (float)((*pCurPtr & 0xFF0000) >> 16);        CGFloat g = (float)((*pCurPtr & 0xFF00) >> 8);        CGFloat b = (float)(*pCurPtr & 0xFF);        //NSLog(@"r:%f g:%f b:%f",r,g,b);        if ((mostR-weight)<=r&&r<=(mostR+weight)&&(mostG-weight)<=g&&g<=(mostG+weight)&&(mostB-weight)<=b&&b<=(mostB+weight)) {            uint8_t* ptr = (uint8_t*)pCurPtr;            // 将白色变成透明            ptr[0] = 0;        }        //        //        else        //        //        {        //        //            // 改成下面的代码,会将图片转成想要的颜色        //        //            uint8_t* ptr = (uint8_t*)pCurPtr;        //        //            ptr[3] = 0; //0~255        //        //            ptr[2] = 0;        //        //            ptr[1] = 0;        //        //        //        }    }    // 将内存转成image        CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);        CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,                                                                                kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider,                                                                                NULL, true, kCGRenderingIntentDefault);        CGDataProviderRelease(dataProvider);                UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];                // 释放        CGImageRelease(imageRef);        CGContextRelease(context);        CGColorSpaceRelease(colorSpace);        // free(rgbImageBuf) 创建dataProvider时已提供释放函数,这里不用free        return resultUIImage;    }
#pragma mark - 获取图片中出现次数最多的RGB
-(NSDictionary*)mostColorFromImage:(UIImage *)image{    #if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;#else    int bitmapInfo = kCGImageAlphaPremultipliedLast;#endif        //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大 50 50    CGSize thumbSize=CGSizeMake(150, 150);        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();    CGContextRef context = CGBitmapContextCreate(NULL,                                                 thumbSize.width,                                                 thumbSize.height,                                                 8,//bits per component                                                 thumbSize.width*4,                                                 colorSpace,                                                 bitmapInfo);        CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);    CGContextDrawImage(context, drawRect, image.CGImage);    CGColorSpaceRelease(colorSpace);                //第二步 取每个点的像素值    unsigned char* data = CGBitmapContextGetData (context);        if (data == NULL) return nil;        NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];        for (int x=0; x<thumbSize.width; x++) {        for (int y=0; y<thumbSize.height; y++) {                        int offset = 4*(x*y);                        int red = data[offset];            int green = data[offset+1];            int blue = data[offset+2];            int alpha =  data[offset+3];                        NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];            [cls addObject:clr];                    }    }    CGContextRelease(context);            //第三步 找到出现次数最多的那个颜色    NSEnumerator *enumerator = [cls objectEnumerator];    NSArray *curColor = nil;        NSArray *MaxColor=nil;    NSUInteger MaxCount=0;        while ( (curColor = [enumerator nextObject]) != nil )    {        NSUInteger tmpCount = [cls countForObject:curColor];                if ( tmpCount < MaxCount ) continue;                MaxCount=tmpCount;        MaxColor=curColor;            }        CGFloat mostR = [MaxColor[1] intValue];    CGFloat mostG = [MaxColor[2] intValue];    CGFloat mostB = [MaxColor[3] intValue];    NSLog(@"mostR:%f mostG:%f mostB:%f",mostR,mostG,mostB);        NSDictionary *dictColor = @{@"red":[NSNumber numberWithFloat:[MaxColor[0] intValue]],@"green":[NSNumber numberWithFloat:[MaxColor[1] intValue]],@"blue":[NSNumber numberWithFloat:[MaxColor[2] intValue]],@"alpha":[NSNumber numberWithFloat:[MaxColor[3] intValue]]};    return dictColor;    //return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:([MaxColor[3] intValue]/255.0f)];}

#pragma mark - 设置图片透明度

- (UIImage *)imageByApplyingAlpha:(CGFloat)alpha  image:(UIImage*)image{        UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0f);                CGContextRef ctx = UIGraphicsGetCurrentContext();        CGRect area = CGRectMake(0, 0, image.size.width, image.size.height);                CGContextScaleCTM(ctx, 1, -1);        CGContextTranslateCTM(ctx, 0, -area.size.height);                CGContextSetBlendMode(ctx, kCGBlendModeMultiply);                CGContextSetAlpha(ctx, alpha);                CGContextDrawImage(ctx, area, image.CGImage);                UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();            UIGraphicsEndImageContext();                return newImage;    }

#pragma mark - 合并2张图片
- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 {    UIGraphicsBeginImageContext(image1.size);                // Draw image1        [image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];    NSLog(@"image1:%@",NSStringFromCGRect(CGRectMake(0, 0, image1.size.width, image1.size.height)));            // Draw image2        [image2 drawInRect:CGRectMake(0, 0, image2.size.width, image2.size.height)];    NSLog(@"image2:%@",NSStringFromCGRect(CGRectMake(0, 0, image2.size.width, image2.size.height)));            UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();    NSLog(@"imageRes:%@",NSStringFromCGRect(CGRectMake(0, 0, resultingImage.size.width, resultingImage.size.height)));    UIGraphicsEndImageContext();        return resultingImage;    }

#pragma mark - 将UIImage缩放到指定大小尺寸
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{        // 创建一个bitmap的context        // 并把它设置成为当前正在使用的context        UIGraphicsBeginImageContext(size);        // 绘制改变大小的图片        [img drawInRect:CGRectMake(0, 0, size.width, size.height)];        // 从当前context中创建一个改变大小后的图片        UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();        // 使当前的context出堆栈        UIGraphicsEndImageContext();        // 返回新的改变大小后的图片        return scaledImage;    }

#pragma mark - 根据图片的大小等比例压缩返回图片
-(UIImage *)fitSmallImage:(UIImage *)image size:(CGSize)size{        if (nil == image)            {                return nil;            }        if (image.size.width&&image.size.height){                return image;            }        UIGraphicsBeginImageContext(size);        CGRect rect = CGRectMake(0, 0, size.width, size.height);        [image drawInRect:rect];        UIImage *newing = UIGraphicsGetImageFromCurrentImageContext();        UIGraphicsEndImageContext();        return newing;    }

#pragma mark - 获取图片点对应的颜色

+ (UIColor*) getPixelColorAtLocation:(CGPoint)point inImage:(UIImage *)image {    UIColor* color = nil;    CGImageRef inImage = image.CGImage;    CGContextRef cgctx = [ViewController 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);        unsigned char* data = CGBitmapContextGetData (cgctx);        if (data != NULL) {        int offset = 4*((w*round(point.y))+round(point.x));        int alpha =  data[offset];        int red = data[offset+1];        int green = data[offset+2];        int blue = data[offset+3];        NSLog(@"offset: %i colors: RGB A %i %i %i  %i",offset,red,green,              blue,alpha);                NSLog(@"x:%f y:%f", point.x, point.y);                color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:                 (blue/255.0f) alpha:(alpha/255.0f)];    }        CGContextRelease(cgctx);        if (data) { free(data); }        return color;    }+ (CGContextRef) createARGBBitmapContextFromImage:(CGImageRef) inImage {        CGContextRef    context = NULL;        CGColorSpaceRef colorSpace;        void *          bitmapData;        int             bitmapByteCount;        int             bitmapBytesPerRow;        size_t pixelsWide = CGImageGetWidth(inImage);        size_t pixelsHigh = CGImageGetHeight(inImage);        bitmapBytesPerRow   = (pixelsWide * 4);        bitmapByteCount     = (bitmapBytesPerRow * pixelsHigh);        colorSpace = CGColorSpaceCreateDeviceRGB();        if (colorSpace == NULL)            {                fprintf(stderr, "Error allocating color space\n");                return NULL;            }        bitmapData = malloc( bitmapByteCount );        if (bitmapData == NULL)            {                fprintf (stderr, "Memory not allocated!");                CGColorSpaceRelease( colorSpace );                return NULL;            }        context = CGBitmapContextCreate (bitmapData,                                                                          pixelsWide,                                                                            pixelsHigh,                                                                            8,                                                                                  bitmapBytesPerRow,                                                                            colorSpace,                                                                            kCGImageAlphaPremultipliedFirst);          if (context == NULL)              {                  free (bitmapData);                  fprintf (stderr, "Context not created!");              }          CGColorSpaceRelease( colorSpace );          return context;      }

参考文章

http://blog.sina.com.cn/s/blog_64cfe8f00101pm3x.html

http://blog.csdn.net/ssanonymity/article/details/7643236

http://www.cocoachina.com/bbs/read.php?tid=181490



0 0
原创粉丝点击