5

I have the following Swift code to make a CGBitmapContext

let imageDirectoryPath:String = "/Users/blah/blah/"
let imageFileName:String = "flower.tif"
let imageNS = NSImage(contentsOfFile: imageDirectoryPath + imageFileName)!
let imageCG = imageNS.CGImageForProposedRect(nil, context: nil, hints: nil)
var rawDataIn:[UInt8] = [UInt8](count: Int(imageNS.size.width) * Int(imageNS.size.height) * 4, repeatedValue: 0xff)
let context = CGBitmapContextCreate(
    &rawDataIn,
    Int(imageNS.size.width),
    Int(imageNS.size.height),
    8,
    Int(imageNS.size.width * 4),
    CGColorSpaceCreateDeviceRGB(),
    CGImageAlphaInfo.PremultipliedLast.rawValue)

I get an error from this, and using Xcode's scheme for the project to set the environment variable CGBITMAP_CONTEXT_LOG_ERRORS I get detail about the error:

Nov 10 10:12:16  SwiftConsoleGrabcut[826] : 
    CGBitmapContextCreate: unsupported parameter combination:
        8 integer bits/component;
        32 bits/pixel;
        RGB color space model; kCGImageAlphaPremultipliedLast;
        19789 bytes/row.
    Valid parameters for RGB color space model are:
        16  bits per pixel,      5  bits per component,      kCGImageAlphaNoneSkipFirst
        32  bits per pixel,      8  bits per component,      kCGImageAlphaNoneSkipFirst
        32  bits per pixel,      8  bits per component,      kCGImageAlphaNoneSkipLast
        32  bits per pixel,      8  bits per component,      kCGImageAlphaPremultipliedFirst
        32  bits per pixel,      8  bits per component,      kCGImageAlphaPremultipliedLast
        64  bits per pixel,      16 bits per component,      kCGImageAlphaPremultipliedLast
        64  bits per pixel,      16 bits per component,      kCGImageAlphaNoneSkipLast
        128 bits per pixel,      32 bits per component,      kCGImageAlphaNoneSkipLast |kCGBitmapFloatComponents
        128 bits per pixel,      32 bits per component,      kCGImageAlphaPremultipliedLast |kCGBitmapFloatComponents
    See Quartz 2D Programming Guide (available online) for more information.

But the parameter combination I use, 32 bits per pixel, 8 bits per component, and kCGImageAlphaPremultipliedLast is one of the supported combinations listed.

Why is it rejected?

This may be a question about size.width. The tif image I am loading into imageNS is 481 pixels wide, but imageNS.size.width is reported as 4947.4285714285716 which may explain the bonkers value given in the error message for bytes per row.

dumbledad
  • 16,305
  • 23
  • 120
  • 273

0 Answers0