问题描述
此代码适用于我(Swift 2游乐场)灰度,并加载彩色.BMP图像...
This code works for me (Swift 2 playground) in Gray scale, loading a colour .BMP image...
...但是如果我将bytesPerPixel
更改为3(或4)并使用
... 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?
推荐答案
您可能忘记了CGImageAlphaInfo参数.对于彩色图像,如果假设bytesPerPixel
为4,则在创建上下文时需要设置RGBA(或ARGB).以下是不具有alpha通道的RGBA的示例.
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
}
这篇关于回复:迅速从UIImage/CGImage获取像素数据作为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!