- 利用kCGBlendModeLuminosit混合模式
- (UIImage *)grayishImage:(UIImage *)inputImage {
CGFloat scale = [UIScreen mainScreen].scale;
UIGraphicsBeginImageContextWithOptions(inputImage.size, YES, scale);
CGRect rect = CGRectMake(0, 0, inputImage.size.width, inputImage.size.height);
[inputImage drawInRect:rect blendMode:kCGBlendModeLuminosity alpha:1.0];
UIImage *filterImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return filterImage;
}
- (UIImage *)convertToGrayImage:(UIImage *)inputImage {
CGImageRef imageRef = [inputImage CGImage];
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
size_t bitsPerComponent = 8;
size_t bytesPerRow = width * 4;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
uint32_t *pixels = (uint32_t *) calloc(bytesPerRow * height, sizeof(uint8_t));
// kCGImageAlphaPremultipliedFirst ARGB
// kCGImageAlphaPremultipliedLast RGBA
// kCGBitmapByteOrder32Little 小端 (低位字节在前)
// kCGBitmapByteOrder32Big 大端 (高位字节在前)
CGContextRef context = CGBitmapContextCreate(pixels, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x];
uint32_t gray = 0.3 * rgbaPixel[0] + 0.59 * rgbaPixel[1] + 0.11 * rgbaPixel[2];
rgbaPixel[0] = gray;
rgbaPixel[1] = gray;
rgbaPixel[2] = gray;
}
}
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
free(pixels);
UIImage *resultImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
return resultImage;
}
- 利用CGColorSpaceCreateDeviceGray()
- (UIImage *)changeToGrayImage:(UIImage *)inputImage {
CGImageRef imageRef = [inputImage CGImage];
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
size_t bitsPerComponent = 8;
size_t bytesPerRow = width * 4;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
uint32_t *pixels = (uint32_t *) calloc(bytesPerRow * height, sizeof(uint8_t));
CGContextRef contextRef = CGBitmapContextCreate(pixels, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
CGContextDrawImage(contextRef, CGRectMake(0, 0, width, height), imageRef);
CGImageRef newImageRef = CGBitmapContextCreateImage(contextRef);
CGContextRelease(contextRef);
CGColorSpaceRelease(colorSpace);
free(pixels);
UIImage *resultImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
return resultImage;
}
网友评论