-
(UIImage *)convertToBlackAndWhiteWithFloydSteinbergDithering:(UIImage *)originalImage {
// 创建灰度色彩空间
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
// 创建位图上下文
CGContextRef context = CGBitmapContextCreate(nil, originalImage.size.width, originalImage.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
CGColorSpaceRelease(colorSpace);if (context == NULL) {
return nil;
}// 绘制原始图像到位图上下文
CGRect imageRect = CGRectMake(0, 0, originalImage.size.width, originalImage.size.height);
CGContextDrawImage(context, imageRect, [originalImage CGImage]);// 获取位图数据
unsigned char *bitmapData = CGBitmapContextGetData(context);
if (bitmapData == NULL) {
CGContextRelease(context);
return nil;
}// 应用 Floyd-Steinberg 抖动算法和误差扩散算法
for (int y = 0; y < originalImage.size.height; y++) {
for (int x = 0; x < originalImage.size.width; x++) {
unsigned char oldPixel = bitmapData[y*(int)originalImage.size.width + x];
unsigned char newPixel = oldPixel < 128 ? 0 : 255;
bitmapData[y*(int)originalImage.size.width + x] = newPixel;
unsigned char error = oldPixel - newPixel;// 误差扩散 if (x + 1 < originalImage.size.width) { bitmapData[y*(int)originalImage.size.width + (x+1)] = MIN(255, MAX(0, bitmapData[y*(int)originalImage.size.width + (x+1)] + error * 7 / 16)); } if (x - 1 >= 0 && y + 1 < originalImage.size.height) { bitmapData[(y+1)*(int)originalImage.size.width + (x-1)] = MIN(255, MAX(0, bitmapData[(y+1)*(int)originalImage.size.width + (x-1)] + error * 3 / 16)); } if (y + 1 < originalImage.size.height) { bitmapData[(y+1)*(int)originalImage.size.width + x] = MIN(255, MAX(0, bitmapData[(y+1)*(int)originalImage.size.width + x] + error * 5 / 16)); } if (x + 1 < originalImage.size.width && y + 1 < originalImage.size.height) { bitmapData[(y+1)*(int)originalImage.size.width + (x+1)] = MIN(255, MAX(0, bitmapData[(y+1)*(int)originalImage.size.width + (x+1)] + error * 1 / 16)); } }
}
// 创建黑白图像
CGImageRef convertedImageRef = CGBitmapContextCreateImage(context);
UIImage *convertedImage = [UIImage imageWithCGImage:convertedImageRef];// 释放资源
CGImageRelease(convertedImageRef);
CGContextRelease(context);return convertedImage;
}
Floyd-Steinberg 抖动误差扩散法-oc
最新推荐文章于 2024-07-21 09:00:00 发布