在Swift中将UIImage转换为UInt8数组

4

大家好!

我一直在研究这个问题,并且在我的项目中集成了几种不同的解决方案,但是它们似乎都无法正常工作。目前我使用的解决方案是从这个帖子借鉴来的。

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

  1. 像素数组仍然被初始化但未填充(全为0)
  2. 我收到了两个错误消息:

    CGBitmapContextCreate:不支持的参数组合:设置CGBITMAP_CONTEXT_LOG_ERRORS环境变量以查看详细信息

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

有什么想法吗?这是我目前为我的图像类调用的构建函数:
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 相关的知识。

非常感谢!


第一步是要删除隐式解包和强制解包的可选项。它们只会导致运行时崩溃和错误。最好检查一个可选项并正确地处理每种情况。 - user887210
1
好的,我会立即处理。 - Ted Lasso
2个回答

4

在调用 CGBitmapContextCreate 函数时,bitmapInfo 参数不应该传入 0。对于 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



这绝对有助于填充数组,尽管我不确定它是否被正确填充。当我立即将其转换回图像时,通道似乎非常混乱。我应该在这里继续还是提出另一个问题? - Ted Lasso

-1

你需要将图像转换为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))

2
这会给您PNG表示,而不是原始像素数据。 - Martin R

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接