-(UIImage *)BackgrounTransparent:(UIImage*)image{
CGImageRef imageRef = image.CGImage;
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
// 构成像素的各个RGB要素为多少bit
size_t bitsPerComponent;
bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
// 像素整体为多少bit构成
size_t bitsPerPixel;
bitsPerPixel = CGImageGetBitsPerPixel(imageRef);
// 画像的横向一行的数据为多少bit构成
size_t bytesPerRow;
bytesPerRow = CGImageGetBytesPerRow(imageRef);
// 画像的色彩空间
CGColorSpaceRef colorSpace = CGImageGetColorSpace(imageRef);
// 画像的Bitmap信息
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
// 画像的像素间的补正是否完成
bool shouldInterpolate;
shouldInterpolate = CGImageGetShouldInterpolate(imageRef);
// 是否根据显示设备来进行了补正
CGColorRenderingIntent intent = CGImageGetRenderingIntent(imageRef);
// 获取画像的数据提供者
CGDataProviderRef dataProvider = CGImageGetDataProvider(imageRef);
// 从数据提供者获取画像的bitmap数据
CFDataRef data;
UInt8* buffer;
data = CGDataProviderCopyData(dataProvider);
buffer = (UInt8*)CFDataGetBytePtr(data);
UInt8 oldred,oldgreen,oldblue,oldAlpha;
UInt8* oldtmp;
oldtmp = buffer ;
oldred=*(oldtmp+0);
oldgreen=*(oldtmp+1);
oldblue=*(oldtmp+2);
oldAlpha=*(oldtmp+3);
NSLog(@"oldred:%d,oldgreen:%d,oldblue:%d,oldalpha:%d",oldred,oldgreen,oldblue,oldAlpha);
NSInteger tolerance =15; //容差
// 一个像素一个像素地处理画像
NSUInteger x, y;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
UInt8* tmp;
tmp = buffer + y * bytesPerRow + x * 4;
// 获取RGB的值
UInt8 red,green,blue,alpha;
red = *(tmp + 0);
green = *(tmp + 1);
blue = *(tmp + 2);
alpha=*(tmp+3);
if (abs(red-oldred)<=tolerance && abs(green-oldgreen)<=tolerance && abs(blue-oldblue)<=tolerance) {
*(tmp + 0) = 0;
*(tmp + 1) = 0;
*(tmp + 2) = 0;
*(tmp + 3) = 0;
}
}
}
// 生成赋予效果的数据
CFDataRef effectedData;
effectedData = CFDataCreate(NULL, buffer, CFDataGetLength(data));
// 生成赋予效果的数据提供者
CGDataProviderRef effectedDataProvider;
effectedDataProvider = CGDataProviderCreateWithCFData(effectedData);
// 生成画像
CGImageRef effectedCgImage;
UIImage* effectedImage;
effectedCgImage = CGImageCreate(
width, height,
bitsPerComponent, bitsPerPixel, bytesPerRow,
colorSpace, kCGImageAlphaLast, effectedDataProvider,
NULL, shouldInterpolate, intent);
effectedImage = [[UIImage alloc] initWithCGImage:effectedCgImage];
CGImageRelease(effectedCgImage);
CFRelease(effectedDataProvider);
CFRelease(effectedData);
CFRelease(data);
return effectedImage;
}
转载自:http://siruoxian.iteye.com/admin/blogs/1979574