在Swift中将UIImage转换为UInt8数组 [英] Convert UIImage to UInt8 Array in Swift

查看:759
本文介绍了在Swift中将UIImage转换为UInt8数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有!

我一直在对此进行大量研究,并且我已经将几种不同的解决方案集成到我的项目中,但它们似乎都没有工作。我目前的解决方案来自此主题

I've been doing a lot of research into this and I've integrated several different solutions into my project, but none of them seem to work. My current solution has been borrowed from this thread.

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

When I run my code, however, two things happen:


  1. 像素阵列保持初始化但未填充(满0)

  2. 我收到两个错误:

  1. The pixel array remains initialized but unpopulated (Full of 0s)
  2. I get two errors:

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

CGBitmapContextCreate: unsupported parameter combination: set CGBITMAP_CONTEXT_LOG_ERRORS environmental variable to see the details

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

任何想法?这是我当前构建的函数,我正在调用我的Image类:

Any ideas? Here is my current built function that I'm calling for my Image class:

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的工作原理。

Any pointers would help a lot, as I'm new to understanding how all of this CGBitmap stuff works.

非常感谢!

推荐答案

你不应该传递 0 作为 bitmapInfo 的参数> CGBitmapContextCreate 。对于RGBA,您应传递 CGImageAlphaInfo.PremultipliedLast.rawValue

You should not pass an 0 as the bitmapInfo param for CGBitmapContextCreate. For RGBA you shall pass 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

Supported combinations of bitsPerComponent, bytesPerRow, colorspace and bitmapInfo can be found here: 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

Note that 32 bits per pixel (bpp) is 4 bytes per pixel and you use it to calculate bytesPerRow

这篇关于在Swift中将UIImage转换为UInt8数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆