更改圖片的顏色蛆封,指定顏色范圍杀糯,這里Color使用的是RGB
例子中是接近白色色值改為透明,根據(jù)需求可修改
原理剖析
- 設(shè)置顏色范圍R(0 ~ 255)彤枢、G(0 ~ 255)狰晚、B(0 ~ 255)
- 遍歷圖片像素,范圍值內(nèi)的color更換指定顏色
代碼
1.給圖片分配內(nèi)存
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);
2.創(chuàng)建上下文context
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
3.遍歷像素
int pixelNum = imageWidth * imageHeight;
uint32_t* pCurPtr = rgbImageBuf;
for (int i = 0; i < pixelNum; i++, pCurPtr++) {
//接近白色
//將像素點轉(zhuǎn)成子節(jié)數(shù)組來表示---第一個表示透明度即ARGB這種表示方式缴啡。ptr[0]:透明度,ptr[1]:R,ptr[2]:G,ptr[3]:B
//分別取出RGB值后壁晒。進(jìn)行判斷需不需要設(shè)成透明。
uint8_t* ptr = (uint8_t*)pCurPtr;
if (ptr[1] > 240 && ptr[2] > 240 && ptr[3] > 240) {
//當(dāng)RGB值都大于240則比較接近白色的都將透明度設(shè)為0
//即接近白色的都設(shè)置為透明业栅。某些白色背景具有雜質(zhì)就會去不干凈秒咐,用這個方法可以去干凈
//改為其他顏色可更改ptr其他值
ptr[0] = 0;
}
}
附:16進(jìn)制篩選方案(根據(jù)需求選擇使用)
//去除白色...將0xFFFFFF00換成其它顏色也可以替換其他顏色。
if ((*pCurPtr & 0xFFFFFF00) >= 0xffffff00) {
uint8_t* ptr = (uint8_t*)pCurPtr;
ptr[0] = 0;
}
4.將內(nèi)存轉(zhuǎn)成image
CGDataProviderRef dataProvider =CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, nil);
CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight,8, 32, bytesPerRow, colorSpace, kCGImageAlphaLast |kCGBitmapByteOrder32Little, dataProvider, NULL, true,kCGRenderingIntentDefault);
CGDataProviderRelease(dataProvider);
UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
resultUIImage
即是更改后得到的Image
5.釋放內(nèi)存(防止內(nèi)存泄漏)
CGImageRelease(imageRef);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);