全部!
我一直在对此进行大量研究,并将几种不同的解决方案集成到我的项目中,但它们似乎都不起作用。我目前的解决方案是从this thread借来的.
但是,当我运行我的代码时,会发生两件事:
- 像素阵列保持初始化但未填充(全为 0)
我遇到两个错误:
CGBitmapContextCreate:不支持的参数组合:设置CGBITMAP_CONTEXT_LOG_ERRORS环境变量查看详情
和
CGContextDrawImage: invalid context 0x0. If you want to see the backtrace, please set
有什么想法吗?这是我正在为我的 Image 类调用的当前内置函数:
init?(fromImage image: UIImage!) {
let imageRef = image!.CGImage
self.width = CGImageGetWidth(imageRef)
self.height = CGImageGetHeight(imageRef)
let colorspace = CGColorSpaceCreateDeviceRGB()
let bytesPerRow = (4 * width);
let bitsPerComponent :UInt = 8
let pixels = UnsafeMutablePointer<UInt8>(malloc(width*height*4))
var context = CGBitmapContextCreate(pixels, width, height, Int(bitsPerComponent), bytesPerRow, colorspace, 0);
CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), imageRef)
任何指针都会有很大帮助,因为我对理解所有这些 CGBitmap 的东西是如何工作的还很陌生。
非常感谢!
最佳答案
您不应将 0
作为 CGBitmapContextCreate
的 bitmapInfo
参数传递。对于 RGBA,您应传递 CGImageAlphaInfo.PremultipliedLast.rawValue
。
可在此处找到受支持的 bitsPerComponent
、bytesPerRow
、colorspace
和 bitmapInfo
组合:
https://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_context/dq_context.html#//apple_ref/doc/uid/TP30001066-CH203-BCIBHHBB
请注意,每像素 32 位 (bpp) 是每像素 4 字节,您可以使用它来计算 bytesPerRow
关于ios - 在 Swift 中将 UIImage 转换为 UInt8 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36416833/