在ios中将图像颜色转换为灰度时出错

时间:2014-02-10 08:17:41

标签: ios uiimage cgcolor

在我的应用程序中,我有一个imageView,然后我按下一个按钮,图像应该更改为黑白

我使用过这种方法

- (UIImage *) convertToGreyscale:(UIImage *)i {

int kRed = 1;
int kGreen = 2;
int kBlue = 4;

int colors = kGreen;
int m_width = i.size.width;
int m_height = i.size.height;

uint32_t *rgbImage = (uint32_t *) malloc(m_width * m_height * sizeof(uint32_t));
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(rgbImage, m_width, m_height, 8, m_width * 4, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextSetShouldAntialias(context, NO);
CGContextDrawImage(context, CGRectMake(0, 0, m_width, m_height), [i CGImage]);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);

// now convert to grayscale
uint8_t *m_imageData = (uint8_t *) malloc(m_width * m_height);
for(int y = 0; y < m_height; y++) {
    for(int x = 0; x < m_width; x++) {
        uint32_t rgbPixel=rgbImage[y*m_width+x];
        uint32_t sum=0,count=0;
        if (colors & kRed) {sum += (rgbPixel>>24)&255; count++;}
        if (colors & kGreen) {sum += (rgbPixel>>16)&255; count++;}
        if (colors & kBlue) {sum += (rgbPixel>>8)&255; count++;}
        m_imageData[y*m_width+x]=sum/count;
    }
}
free(rgbImage);

// convert from a gray scale image back into a UIImage
uint8_t *result = (uint8_t *) calloc(m_width * m_height *sizeof(uint32_t), 1);

// process the image back to rgb
for(int i = 0; i < m_height * m_width; i++) {
    result[i*4]=0;
    int val=m_imageData[i];
    result[i*4+1]=val;
    result[i*4+2]=val;
    result[i*4+3]=val;
}

// create a UIImage
colorSpace = CGColorSpaceCreateDeviceRGB();
context = CGBitmapContextCreate(result, m_width, m_height, 8, m_width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
CGImageRef image = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
UIImage *resultUIImage = [UIImage imageWithCGImage:image];
CGImageRelease(image);

free(m_imageData);

// make sure the data will be released by giving it to an autoreleased NSData
[NSData dataWithBytesNoCopy:result length:m_width * m_height];

return resultUIImage;
}

并在buttton点击方法中调用它

 [self convertToGreyscale:cameraPageView.imageView.image];  

但是没有任何变化,在图片中,任何人都可以帮助我在哪里出错

1 个答案:

答案 0 :(得分:0)

除了算法中的一些错误(灰度不是r,g,b的平均值),主要问题是图像是不可变的。您没有修改图像(自我),而是创建一个新图像。