ios - 在 Swift 中将 UIImage 转换为 UInt8 数组

标签 ios arrays swift image

全部!

我一直在对此进行大量研究,并将几种不同的解决方案集成到我的项目中,但它们似乎都不起作用。我目前的解决方案是从this thread借来的.

但是,当我运行我的代码时,会发生两件事:

  1. 像素阵列保持初始化但未填充(全为 0)
  2. 我遇到两个错误:

    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 作为 CGBitmapContextCreatebitmapInfo 参数传递。对于 RGBA,您应传递 CGImageAlphaInfo.PremultipliedLast.rawValue


可在此处找到受支持的 bitsPerComponentbytesPerRowcolorspacebitmapInfo 组合: 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/

相关文章:

swift - 需要各种 NSObject 子类型的协议(protocol),无法为 'NSObject' 返回 'Self'

ios - 无用约束个人热点启动栏

ios - 如何减少 UITextView 顶部的 "empty space"

ios - 根据选择自动向下滚动

javascript - 仅打印单击的单选按钮值(React)

ios - swift 数组 : how to append element references in order to update element later on from a synch request?

java - 将二维数组复制到一维数组

iphone - NSGenericException,NSMutableArray 给出了一些问题

swift - Tableview 原型(prototype)单元高于其他单元

ios - PageviewController 选择索引到特定的 viewcontroller