1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#define Mask8(x) ( (x) & 0xFF)
#define R(x) ( Mask8(x) )
#define G(x) ( Mask8(x >> 8 ) )
#define B(x) ( Mask8(x >> 16) )
#define A(x) ( Mask8(x >> 24) )
#define RGBAMake(r, g, b, a) ( Mask8(r) | Mask8(g) << 8 | Mask8(b) << 16 | Mask8(a) << 24 )
- (UIImage *)processUsingPixels:(UIImage *)image{
//1.获得图片的像素 以及上下文
UInt32 *inputPixels;
CGImageRef inputCGImage = [image CGImage];
size_t w = CGImageGetWidth(inputCGImage);
size_t h = CGImageGetHeight(inputCGImage);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSInteger bytesPerPixel = 4;//每个像素的字节数
NSInteger bitsPerComponent = 8;//每个组成像素的 位深
NSInteger bitmapBytesPerRow = w * bytesPerPixel;//每行字节数
inputPixels = (UInt32 *)calloc(w * h , sizeof(UInt32));//通过calloc开辟一段连续的内存空间
CGContextRef context = CGBitmapContextCreate(inputPixels, w, h, bitsPerComponent, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, w, h), inputCGImage);
//2取具体某一个像素点的值
for (NSInteger j = 0; j < h; j ++) {
for (NSInteger i = 0 ; i < w; i ++) {
UInt32 *currentPixel = inputPixels + (w * j) + i;
UInt32 color = *currentPixel;
//灰度图
UInt32 max = MAX(MAX(R(color), G(color)), B(color));
*currentPixel = RGBAMake(max, max, max, A(color));
}
}
//3从上下文中取出
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
//4释放
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
free(inputPixels);
return newImage;
}