+ (UIImage*) imageToTransparent:(UIImage*) image
{
// 分配内存
const int imageWidth = image.size.width;
const int imageHeight = image.size.height;
size_t bytesPerRow = imageWidth * 4;
//初始化一个RGB图像流
uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
// 创建context,设置RGB图像流
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
CGColorSpaceRelease(colorSpace);
//RGB图像流接受图像
CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
CGContextRelease(context);
// 遍历像素
int pixelNum = imageWidth * imageHeight;
uint32_t* pCurPtr = rgbImageBuf;//
for (int i = 0; i < pixelNum; i++, pCurPtr++)
{
// 分离三原色及透明度
int red = ((*pCurPtr & 0xFF000000) >> 24);
int green = ((*pCurPtr & 0x00FF0000) >> 16);
int blue = ((*pCurPtr & 0x0000FF00) >> 8);
int alpha = ((*pCurPtr & 0x000000FF) >> 0);
int avg = (red + green +blue)/3;
// 此处可做二值化处理
uint32_t* ptr = (uint32_t*)pCurPtr;
ptr[0] = avg << 24 | avg << 16 | avg << 8
| alpha;
}
// 将内存转成image用CGDataProviderRef接受
CGDataProviderRef dataProvider =CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight,8, 32, bytesPerRow, colorSpace,
kCGImageAlphaLast |kCGBitmapByteOrder32Little, dataProvider,
NULL, true,kCGRenderingIntentDefault);
// 释放CGDataProviderRef
CGDataProviderRelease(dataProvider);
UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
// 释放CGImageRef
CGImageRelease(imageRef);
return resultUIImage;
}
/** 颜色变化 */
void ProviderReleaseData (void *info, const void *data, size_t size)
{
free((void*)data);
}
ios 创建二值化 灰度图
最新推荐文章于 2021-03-11 16:41:53 发布