在Swift中将UIImage转换为UInt8数组

所有!

我已经做了大量的研究,并且已经将几种不同的解决scheme整合到了我的项目中,但是他们都没有工作。 我现在的解决scheme已经从这个线程借用。

当我运行我的代码时,发生了两件事情:

  1. 像素arrays保持初始化但未填充(满0)
  2. 我得到两个错误:

    CGBitmapContextCreate:不支持的参数组合:设置CGBITMAP_CONTEXT_LOG_ERRORS环境variables来查看细节

CGContextDrawImage: invalid context 0x0. If you want to see the backtrace, please set 

有任何想法吗? 这里是我目前为我的Image类调用的构build函数:

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


bitsPerComponentbytesPerRowcolorspacebitmapInfo支持组合可以在这里find: 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


您需要将图像转换为NSData,然后将NSData转换为UInt8数组。

 let data: NSData = UIImagePNGRepresentation(image) // or let data: NSData = UIImageJPGRepresentation(image) let count = data.length / sizeof(UInt8) // create an array of Uint8 var array = [UInt8](count: count, repeatedValue: 0) // copy bytes into array data.getBytes(&array, length:count * sizeof(UInt8))