title: How to read and log the raw pixels of image in swift iOS
body: <p>I need to read pixel values of an image and iterate to print in swift output, I have written this so far and used a <code>RGBAImage</code> class to read out pixels. I'm getting lost from <code>CGContextRef</code> to Iteration. I tried to write from CGImage, getting pixel data from objective C language to swift since I wanted to work in swift.</p>
  
  <pre><code>func createRGBAPixel(inImage: CGImageRef) -&gt; CGContextRef {
  //Image width, height
  
  let pixelWidth = CGImageGetWidth(inImage)
  let pixelHeight = CGImageGetHeight(inImage)
  
  //Declaring number of bytes 
  
  let bytesPerRow = Int(pixelWidth) * 4
  let byteCount = bytesPerRow * Int(pixelHeight)
  
  //RGB color space
  
  let colorSpace = CGColorSpaceCreateDeviceRGB()
  
  //Allocating image data
  
  let mapData = malloc(byteCount)
  let mapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
  
  //Create bitmap context
  
  let context = CGBitmapContextCreate(mapData, pixelWidth, pixelHeight, Int(8), Int(bytesPerRow), colorSpace, mapInfo.rawValue)
  
  let pixelImage = CGBitmapContextCreate(pixels, pixelWidth, pixelHeight, bitsPerComponent, bytesPerRow, colorSpace, mapInfo)
  let CGContextRef = pixelImage
  let CGContextDrawImage(context, CGRectMake(0, 0, pixelWidth, pixelHeight), inImage)
  
  //Iterating and logging
  print("Logging pixel counts")
  let pixels = calloc(pixelHeight * pixelWidth, sizeof(UInt32))
  
  let myImage = CGImageRef: inImage
  let myRGBA = RGBAImage(image: myImage)! //RGBAImage class to read pixels.
  
  var number = 0
  var currentPixel:Int32 = 0
  currentPixel = pixels * UInt32
  for number in 0..&lt;pixelHeight {
    for number in 0..&lt;pixelWidth {
      var color = color * currentPixel
      print((pixel.red + pixel.green + pixel.blue) / 3.0)
      currentPixel++
    }
  }
  return context!
  }
  </code></pre>