How read pixel in CGBitmapContextCreate

In un tutorial by RayWenderlichwrite in Objective-C

explains how to create a bitmap Image, but a lot has changed in Swift:

is right set :

let pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(1)
let context:CGContextRef = CGBitmapContextCreate(pixel, width, height, bitsPerComponent, bytesForRow, colorSpace, bitmapInfo.rawValue)!

and how make translate this code for print the value of RGB:

#define Mask8(x) ( (x) & 0xFF )
#define R(x) ( Mask8(x) )
#define G(x) ( Mask8(x >> 8 ) )
#define B(x) ( Mask8(x >> 16) )

  /
  NSLog(@"Brightness of image:");
  UInt32 * currentPixel = pixels;
  for (NSUInteger j = 0; j < height; j++) {
    for (NSUInteger i = 0; i < width; i++) {
      UInt32 color = *currentPixel;
      printf("%3.0f ", (R(color)+G(color)+B(color))/3.0);
      currentPixel++;
    }
    printf("\n");
  }

  free(pixels);

#undef R
#undef G
#undef B


I thank everyone who can help me !!!!!

I corrected the method, but I'm sure can be do best:

        let bitmapByteCount:Int = bytesForRow * height
        let imagePointer = UnsafeMutablePointer<Int>.alloc(bitmapByteCount)
        let context:CGContextRef = CGBitmapContextCreate(imagePointer, width, height, bitsPerComponent, bytesForRow, colorSpace, bitmapInfo.rawValue)!

for read values of pixel use this:

let newImagePointer = UnsafeMutablePointer<UInt8>.alloc(imageDataLength)
       
        for pixelColorInfoStartIndex in 0..<(imageDataLength / 4) {
            let currentPixelRedIndex = pixelColorInfoStartIndex * 4
            let currentPixelGreenIndex = currentPixelRedIndex + 1
            let currentPixelBlueIndex = currentPixelRedIndex + 2
            let currentPixelAlphaIndex = currentPixelRedIndex + 3
           
            let redC = data[currentPixelRedIndex]
            let greenC = data[currentPixelGreenIndex]
            let blueC = data[currentPixelBlueIndex]
            let alphaC = data[currentPixelAlphaIndex]
           
            print("RGBA: \(redC) - \(greenC) - \(blueC) - \(alphaC)")
        }

To create CGBitmapContext:

    let context:CGContextRef = CGBitmapContextCreate(nil, width, height, bitsPerComponent, 0, colorSpace, bitmapInfo.rawValue)!

You have no need to alloc data yourself. With passing nil, `CGBitmapContextCreate` will allocate the region needed and when the bitmapContext released, it automatically deallocates the region.


To retrieve tha values or pointers needed to access the bitmap data:

    let height = CGBitmapContextGetHeight(context)
    let bytesPerRow = CGBitmapContextGetBytesPerRow(context)
    let imageDataLength = bytesPerRow * height
   
    let imagePointer = CGBitmapContextGetData(context)
    let data = UnsafePointer<CUnsignedChar>(imagePointer)

Thank you very much

How read pixel in CGBitmapContextCreate
 
 
Q