[iOS 图像处理相关]

//使用CGImage获取并修改图片像素

#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*)inputImage { // 1. Get the raw pixels of the image //定义最高32位整形指针 *inputPixels UInt32 * inputPixels; //转换图片为CGImageRef,获取参数:长宽高,每个像素的字节数(4),每个R的比特数 CGImageRef inputCGImage = [inputImage CGImage]; NSUInteger inputWidth = CGImageGetWidth(inputCGImage); NSUInteger inputHeight = CGImageGetHeight(inputCGImage); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); NSUInteger bytesPerPixel = 4; NSUInteger bitsPerComponent = 8; //每行字节数 NSUInteger inputBytesPerRow = bytesPerPixel * inputWidth; //开辟内存区域,指向首像素地址 inputPixels = (UInt32 *)calloc(inputHeight * inputWidth, sizeof(UInt32)); //根据指针,前面的参数,创建像素层 CGContextRef context = CGBitmapContextCreate(inputPixels, inputWidth, inputHeight, bitsPerComponent, inputBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); //根据目前像素在界面绘制图像 CGContextDrawImage(context, CGRectMake(0, 0, inputWidth, inputHeight), inputCGImage); //接来下就是重点了!!!像素处理-------------------------------------------------------- for (NSUInteger j = 0; j < inputHeight; j++) { for (NSUInteger i = 0; i < inputWidth; i++) { UInt32 * currentPixel = inputPixels + (j * inputWidth) + i; UInt32 color = *currentPixel; UInt32 br,thisR,thisG,thisB,thisA; //这里直接移位获得RBGA的值,以及输出写的非常好! thisR=R(color); thisG=G(color); thisB=B(color); thisA=A(color); //NSLog(@"%d,%d,%d,%d",thisR,thisG,thisB,thisA); br=B(color)-R(color); *currentPixel = RGBAMake(br, br, br, A(color)); } } //创建新图 // 4. Create a new UIImage CGImageRef newCGImage = CGBitmapContextCreateImage(context); UIImage * processedImage = [UIImage imageWithCGImage:newCGImage]; //释放 // 5. Cleanup! CGColorSpaceRelease(colorSpace); CGContextRelease(context); free(inputPixels); return processedImage; }

 

//=======图像缩放====================================================================
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    NSLog(@"准备图像裁剪》》》》缩放后图片大小:width %f height %f ",scaledImage.size.width,scaledImage.size.height);
    
    UIGraphicsEndImageContext();
    return scaledImage;
}

 

posted @ 2015-03-21 12:44  Rayshen  阅读(546)  评论(0编辑  收藏  举报