Ted Lasso
Ted Lasso

Reputation: 131

Convert UIImage to UInt8 Array in Swift

all!

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. The pixel array remains initialized but unpopulated (Full of 0s)
  2. I get two errors:

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

and

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

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)

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

Thanks a ton!

Upvotes: 4

Views: 3468

Answers (2)

w____
w____

Reputation: 3605

You should not pass an 0 as the bitmapInfo param for CGBitmapContextCreate. For RGBA you shall pass CGImageAlphaInfo.PremultipliedLast.rawValue.


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

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


Upvotes: 4

Christian Abella
Christian Abella

Reputation: 5797

You need to convert the image to NSData and then convert NSData to UInt8 array.

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))

Upvotes: -1

Related Questions