我如何操作Xcode中的CGImageRef中的像素值

我有一些

CGImageRef cgImage = "something" 

有没有办法来操纵这个CGImage的像素值? 例如,如果这个图像包含0.0001和3000之间的值,因此当我尝试查看或释放图像在NSImageView( 如何使用CGImageRef图像在NSView中显示图像 )

我得到一个黑色的图像,所有的像素是黑色的,我认为这是与设置像素范围值在不同的颜色映射(我不知道)。

我希望能够操纵或更改像素值,或者只能通过操纵色彩图范围来查看图像。

我已经试过,但显然这是行不通的:

 CGContextDrawImage(ctx, CGRectMake(0,0, CGBitmapContextGetWidth(ctx),CGBitmapContextGetHeight(ctx)),cgImage); UInt8 *data = CGBitmapContextGetData(ctx); for (**all pixel values and i++ **) { data[i] = **change to another value I want depending on the value in data[i]**; } 

谢谢,

为了操纵图像中的个别像素

  • 分配一个缓冲区来保存像素
  • 使用该缓冲区创build一个内存位图上下文
  • 将图像绘制到将像素放入缓冲区的上下文中
  • 根据需要更改像素
  • 从上下文创build一个新的图像
  • 释放资源(注意一定要检查使用仪器的泄漏)

下面是一些示例代码,以帮助您入门。 这段代码将交换每个像素的蓝色和红色分量。

 - (CGImageRef)swapBlueAndRedInImage:(CGImageRef)image { int x, y; uint8_t red, green, blue, alpha; uint8_t *bufptr; int width = CGImageGetWidth( image ); int height = CGImageGetHeight( image ); // allocate memory for pixels uint32_t *pixels = calloc( width * height, sizeof(uint32_t) ); // create a context with RGBA pixels CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate( pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast ); // draw the image into the context CGContextDrawImage( context, CGRectMake( 0, 0, width, height ), image ); // manipulate the pixels bufptr = (uint8_t *)pixels; for ( y = 0; y < height; y++) for ( x = 0; x < width; x++ ) { red = bufptr[3]; green = bufptr[2]; blue = bufptr[1]; alpha = bufptr[0]; bufptr[1] = red; // swaps the red and blue bufptr[3] = blue; // components of each pixel bufptr += 4; } // create a new CGImage from the context with modified pixels CGImageRef resultImage = CGBitmapContextCreateImage( context ); // release resources to free up memory CGContextRelease( context ); CGColorSpaceRelease( colorSpace ); free( pixels ); return( resultImage ); }