CGContextDrawImage error, how to allocate the buffer?

731 Views Asked by At

I am trying to store image data in buffer in my app so i will be able to use it however I get EXC_BAD_ACCESS error on CGContextDrawImage line. Here is the code i am using:

resizedImage.Array() // resizedImage - resized image of 280x140 pixels size
    func Array() {
        let dataBuffer = UnsafeMutablePointer<CUnsignedChar>.alloc(156800) //alloc(156800)
        memset(dataBuffer, 0, 156800)
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.ByteOrder32Big.rawValue | CGImageAlphaInfo.PremultipliedLast.rawValue)
        let context = CGBitmapContextCreate(dataBuffer, 280, 140, 8, 156800, colorSpace, bitmapInfo.rawValue)
        let imageRef = CGImageCreateWithImageInRect(CGImage, CGRectMake(0, 0, 280, 140))
        let rectMake = CGRectMake(0, 0, 280, 140)
        CGContextDrawImage(context, rectMake, imageRef)

return
}

When trying to set buffer and bytes as null and 0 as in apple documentation for automatic memory allocation app doesn't crash, but it gives this errors:

Sep 17 17:18:33  VideoTester[4846] <Error>: CGBitmapContextCreate: invalid data bytes/row: should be at least 1120 for 8 integer bits/component, 3 components, kCGImageAlphaPremultipliedLast.
Sep 17 17:18:33  VideoTester[4846] <Error>: CGContextDrawImage: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.

Seems like I am missing something but can't really figure it out, any advice is needed, thank you!

1

There are 1 best solutions below

0
Alexey Demidov On

Got this working with a help of peacer212, everything seems to work as needed without any errors, here is a working code:

var dataBuffer = [UInt8](count: 280*140 * 4, repeatedValue: 0)

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.ByteOrder32Big.rawValue | CGImageAlphaInfo.PremultipliedLast.rawValue)

        let context = CGBitmapContextCreate(&dataBuffer, 280, 140, 8, 1120, colorSpace, bitmapInfo.rawValue)
        let imageRef = CGImageCreateWithImageInRect(CGImage, CGRectMake(0, 0, 280, 140))
        let rectMake = CGRectMake(0, 0, 280, 140)

        CGContextDrawImage(context, rectMake, imageRef)