Re: Get pixel data as array from UIImage/CGImage in swift

。_饼干妹妹 提交于 2019-12-12 03:36:17

问题


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:


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
}


来源:https://stackoverflow.com/questions/35944602/re-get-pixel-data-as-array-from-uiimage-cgimage-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!