1

我有一些

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]**;
        }

谢谢,

4

1 回答 1

2

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

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

这里有一些示例代码可以帮助您入门。此代码将交换每个像素的蓝色和红色分量。

- (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 );
}
于 2014-06-06T22:35:52.837 回答