iOS 圖片底色更換

更改圖片的顏色,指定顏色范圍,這里Color使用的是RGB
例子中是接近白色色值改為透明,根據(jù)需求可修改

原理剖析

  1. 設(shè)置顏色范圍R(0 ~ 255)、G(0 ~ 255)、B(0 ~ 255)
  2. 遍歷圖片像素,范圍值內(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值后。進行判斷需不需要設(shè)成透明。
    uint8_t* ptr = (uint8_t*)pCurPtr;
    
    if (ptr[1] > 240 && ptr[2] > 240 && ptr[3] > 240) {
        //當RGB值都大于240則比較接近白色的都將透明度設(shè)為0
        //即接近白色的都設(shè)置為透明。某些白色背景具有雜質(zhì)就會去不干凈,用這個方法可以去干凈
        //改為其他顏色可更改ptr其他值
        ptr[0] = 0;
    }
}

附:16進制篩選方案(根據(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);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容