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 に答える