0

This code works for me (Swift 2 playground) in Gray scale, loading a colour .BMP image...

Get pixel data as array from UIImage/CGImage in swift

... but if I change bytesPerPixel to 3 (or 4) and use

let colorSpace = CGColorSpaceCreateDeviceRGB()

...the code still runs with no errors, but pixel values are all zeros. Any suggestions as to how to fix that?

1
  • Never mind what the other post says. Please post a link to the image you're starting with and show in full the actual code you are using. Commented Mar 11, 2016 at 16:19

1 Answer 1

0

You probably forgot the CGImageAlphaInfo parameter. For color images, if you assume bytesPerPixel to be 4, you need to set either RGBA (or ARGB) when creating the context. Following is an example for RGBA without the alpha channel.

// RGBA format
let ctx = CGBitmapContextCreate(&data, pixelsWide, pixelsHigh, 8,   
    bitmapBytesPerRow, colorSpace, CGImageAlphaInfo.NoneSkipLast.rawValue)

According to the documentation, you have these options:

enum CGImageAlphaInfo : UInt32 {
    case None
    case PremultipliedLast
    case PremultipliedFirst
    case Last
    case First
    case NoneSkipLast
    case NoneSkipFirst
    case Only
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks megakilo. I knew alpha was the problem and I had found the parameters, but wasn't aware of the crucial .rawvalue! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.