繁体   English   中英

将图像转换为灰度

[英]Convert image to gray scale

在我的应用程序中,我有一个UIImageView ,在此UIImageView顶部有一个背景色清晰的UIView

我正在使用UIBezierPath在此UIView上释放手绘图,以便用户似乎在UIImageViewUIImage进行绘图。

我正在为UIBezierPath颜色添加透明度。

我的问题是,当我最初在UIImageView加载UIImage ,如何使UIImage具有灰度外观,并且当用户在屏幕上移动手指时,会向用户显示UIImage的原始颜色吗?

正确的方法是使用Core Image,然后编写自己的可在彩色图像上运行的Core Image滤镜。 通过在滤镜上设置一些属性,它将知道用彩色绘制某些部分,但将其他区域转换为灰度。

也就是说,这不是一个琐碎的工作。 您可能可以一起破解其他东西,但可能会变得生涩且不流畅。 “核心图像”滤镜的工作级别与“核心动画”的工作级别相同(在GPU附近),因此如果您采用这种方式,它将非常有效。

触摸时,调用此函数可返回灰度图像。 触摸结束时,为UIImageView设置原始图像。

- (UIImage*)imageWithGrayScaleImage:(UIImage*)inputImg
{   
//Creating image rectangle
//CGRect imageRect = CGRectMake(0, 0, inputImg.size.width / (CGFloat)[inputImg scale], inputImg.size.height / (CGFloat)[inputImg scale]);
CGRect imageRect = CGRectMake(0, 0, inputImg.size.width, inputImg.size.height);

//Allocating memory for pixels
int width = imageRect.size.width;
int height = imageRect.size.height;

uint32_t *pixels = (uint32_t*)malloc(width * height * sizeof(uint32_t));

//Clearing the memory to preserve any transparency.(Alpha)
memset(pixels, 0, width * height * sizeof(uint32_t));

//Creating a context with RGBA pixels
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);

//Drawing the bitmap to the context which will fill the pixels memory
CGContextDrawImage(context, imageRect, [inputImg CGImage]);

//Indices as ARGB or RGBA
const int RED = 1;
const int GREEN = 2;
const int BLUE = 3;

for (int y = 0; y < height; y++)
{
    for (int x = 0; x < width; x++)
    {
        uint8_t* rgbaPixel = (uint8_t*)&pixels[y * width + x];

        //Calculating the grayScale value
        uint32_t grayPixel = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE];

        //Setting the pixel to gray
        rgbaPixel[RED] = grayPixel;
        rgbaPixel[GREEN] = grayPixel;
        rgbaPixel[BLUE] = grayPixel;
    }
}

//Creating new CGImage from the context with modified pixels
CGImageRef newCGImage = CGBitmapContextCreateImage(context);

//Releasing resources to free up memory
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
free(pixels);

//Creating UIImage for return value
//UIImage* newUIImage = [UIImage imageWithCGImage:newCGImage scale:(CGFloat)[inputImg scale] orientation:UIImageOrientationUp];
UIImage* newUIImage = [UIImage imageWithCGImage:newCGImage];

//Releasing the CGImage
CGImageRelease(newCGImage);

return newUIImage;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM