UIImage+CNGray.m 1.65 KB
//
//  UIImage+CNGray.m
//  CNLiveScioLive
//
//  Created by CNLive on 2021/4/27.
//  Copyright © 2021 CNLive. All rights reserved.
//

#import "UIImage+CNGray.h"

@implementation UIImage (CNGray)
+ ( UIImage *)grayImage:( UIImage *)sourceImage {
    const int RED = 1;
    const int GREEN = 2;
    const int BLUE = 3;
    CGRect imageRect = CGRectMake(0, 0, sourceImage.size.width *sourceImage.scale, sourceImage.size.height *sourceImage.scale);
    int width = imageRect.size.width;
    int height = imageRect.size.height;
    uint32_t *pisels = (uint32_t *)malloc(width*height *sizeof(uint32_t));
    memset(pisels, 0, width *height *sizeof(uint32_t));
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pisels, width, height, 8, width *sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little|kCGImageAlphaPremultipliedLast);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), [sourceImage CGImage]);
    for (int y = 0; y < height; y ++) {
        for (int x = 0; x<width; x++) {
            uint8_t *rgbaPixel = (uint8_t *)&pisels[y*width +x];
            uint32_t gray = 0.3 *rgbaPixel[RED] + 0.59 *rgbaPixel[GREEN] + 0.11 *rgbaPixel[BLUE];
            rgbaPixel[RED] = gray;
            rgbaPixel[GREEN] = gray;
            rgbaPixel[BLUE] = gray;
        
        }
    }
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    free(pisels);
    UIImage *resultImage = [UIImage imageWithCGImage:imageRef scale:sourceImage.scale orientation:UIImageOrientationUp];
    CGImageRelease(imageRef);
    return  resultImage;
}
@end