4

I am trying to convert images/textures (for SpriteKit) to grayscale with CoreImage in Swift :

I found this answer : https://stackoverflow.com/a/17218546/836501 which I try to convert to swift for iOS7/8

But kCGImageAlphaNone doesn't exist. Instead I can use CGImageAlphaInfo.None but the function CGBitmapContextCreate() doesn't like it as its last parameter. I am obliged to use the enum CGBitmapInfo but there doesn't seem to be the kCGImageAlphaNone equivalent inside.

This is the full line with the wrong parameter (last one) :

var context = CGBitmapContextCreate(nil, UInt(width), UInt(height), 8, 0, colorSpace, kCGImageAlphaNone)

I just need a way to convert UIImage to grayscale in Swift.

Community
  • 1
  • 1
Kalzem
  • 7,320
  • 6
  • 54
  • 79
  • Similar question here: http://stackoverflow.com/questions/26640037/swift-opengl-unresolved-identifier-kcgimagealphapremultipliedlast. – Martin R Dec 10 '14 at 15:12
  • Thanks @MartinR, do you mind answering with a copy+paste so I can accept your answer ? I guess some will try to close this question because of duplicate, but I wouldn't do it. I tried to look for my problem with the keyword `kCGImageAlphaNone` and couldn't find anything, some may do the same kind of research ;] – Kalzem Dec 10 '14 at 15:20
  • Would `CGBitmapInfo.ByteOrder32Little | CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)` work? – gabbler Dec 10 '14 at 15:21

2 Answers2

12

You have to create a struct CGBitmapInfo from the CGImageAlphaInfo.None value:

let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.None.rawValue)
var context = CGBitmapContextCreate(nil, UInt(width), UInt(height), 8, 0, colorSpace, bitmapInfo)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 8
    Via [this answer](http://stackoverflow.com/a/29957352/255489): as of Swift 2.0, you can just pass `CGImageAlphaInfo.NoneSkipFirst.rawValue` directly to `CGBitmapContextCreate`. – Zev Eisenberg Oct 19 '15 at 14:48
1

I believe the original Objective-C code was wrong. The kCGImageAlphaNone enum value was not the appropriate type to be passing, but Objective-C is less type safe (an enum is an enum) so it worked. The raw value of kCGImageAlphaNone is 0, so passing CGBitmapInfo.allZeros or CGBitmapInfo.ByteOrderDefault (both of which have raw values of 0) should give you the same results.

vacawama
  • 150,663
  • 30
  • 266
  • 294