![](/img/trans.png)
[英]How to convert UnsafeMutablePointer<UInt8> to UIImage in Swift
[英]Convert UIImage to UInt8 Array in Swift
所有!
我一直在对此进行大量研究,并且已经将几种不同的解决方案集成到我的项目中,但它们似乎都没有。 我目前的解决方案是从这个线程借来的。
但是,当我运行我的代码时,会发生两件事:
我收到两个错误:
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
作为bitmapInfo
参数CGBitmapContextCreate
。 对于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
您需要将图像转换为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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.