圖像處理是軟件開發(fā)中很重要的一門技術(shù)腺毫,像ps晤硕,各種美顏app,主要就是運用到它钥顽。
在apple相關(guān)開發(fā)領(lǐng)域义屏,圖像處理主要有下面幾種技術(shù):
. 直接修改位圖圖像
. 使用Core Graphics庫
. 使用Core Image庫
. 使用GPUImage第三方庫
. 使用OpenCV第三方庫
其中,直接修改位圖圖像是圖像處理的基礎(chǔ),不管你多高明的算法闽铐,歸根結(jié)底是要修改原圖每個像素的顏色值和透明度蝶怔。
下面的方法創(chuàng)建一個圖片的緩存數(shù)據(jù),把各個像素的顏色值存進一個數(shù)組里以供修改兄墅。
- (void)createImageBuffer:(UIImage*)source{
? ? ? CGImageRef inputImage = source.CGImage;
? ? ? NSUInteger width = source.size.width;
? ? ? NSUInteger height = source.size.height;
? ? ? NSUInteger bytesPerPixel =4;// 每個像素4個字節(jié)表示
? ? ? NSUInteger bytesPerRow = bytesPerPixel * width;
? ? ? NSUInteger bitsPerComponent = 8;// 應(yīng)該是每個顏色通道由8個bit位表示
? ? ? UInt32* pixels;
? ? ? pixels = (UInt32*)calloc(width * height,sizeof(UInt32));
? ? ?CGColorSpaceRefcolorSpace =CGColorSpaceCreateDeviceRGB();
? ? ?CGContextRefcontext =CGBitmapContextCreate(pixels, width, ? ? ?height, bitsPerComponent, bytesPerRow, ? ? colorSpace,kCGImageAlphaPremultipliedLast|kCGBitmapByteOrder32Big);
// 創(chuàng)建一個容器CGBitmapContext,將像素指針參數(shù)傳遞到容器中
CGContextDrawImage(context,CGRectMake(0,0, width, height), inputImage);
// 這句要有踢星,不然數(shù)據(jù)寫不到pixels數(shù)組中
}
pixels數(shù)組里就是圖片數(shù)據(jù),可以通過如下方式修改:
for(NSUIntegerj =0; j < height; j++) {
for(NSUIntegeri =0; i < width; i++) {
UInt32* currentPixel = pixels + (j * width) + i;
UInt32color = *currentPixel;
UInt32thisR,thisG,thisB,thisA;
//這里直接移位獲得RBGA的值
thisR=R(color);
thisG=G(color);
thisB=B(color);
thisA=A(color) *.5;// 這里是通過把每個像素的透明度乘以.5以改變整個圖的透明度
*currentPixel =RGBAMake(thisR, thisG, thisB, thisA);
}
}
修改圖片數(shù)據(jù)后隙咸,可以通過
CGImageRef ref =CGBitmapContextCreateImage(context);
UIImage* image = [UIImageimageWithCGImage:ref];
獲取到修改后的圖片
當(dāng)然沐悦,完成后還要釋放相關(guān)變量
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
free(pixels);
需要用到這些宏定義:
#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 )
關(guān)于原點坐標(biāo)的問題:
UIImage和UIView使用的是左上原點坐標(biāo),NSImage五督,NSView藏否,Core Image和Core Graphics使用的是左下原點坐標(biāo)
關(guān)于渲染的問題:
1 當(dāng)前屏幕渲染:在GPU的當(dāng)前屏幕緩沖區(qū)中進行的渲染
2 離屏渲染:在GPU當(dāng)前屏幕緩沖區(qū)外另建緩沖區(qū)渲染
3 CPU渲染:如重寫drawRect,用到core graphics技術(shù)繪圖(特殊的離屏渲染)
.. 2比1效率低概荷,因為要新建緩沖區(qū)秕岛,要切換緩沖區(qū)的上下文
.. 3比起1,2误证,缺點是CUP的浮點運算能力比GPU差
.. 盡量用1继薛,對于簡單的效果,3又比2強愈捅,因為運算能力的略勢比不上創(chuàng)建緩沖區(qū)和切換上下文的消耗