Created
January 29, 2019 10:07
-
-
Save knightbenax/4800232e64f04b53d04c380a01b86e22 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getIfImageHasTransparentBackground(image: NSImage) -> Bool { | |
var hasTransparentBackground : Bool = false | |
let cgImage = image.cgImage | |
let context = createARGBBitmapContextFromImage(cgImage: cgImage!) | |
let height = cgImage!.height | |
let width = cgImage!.width | |
let rect: CGRect = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)) | |
context?.draw(cgImage!, in: rect) | |
let pixelData = image.cgImage!.dataProvider!.data | |
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) | |
//Filter through data and look for non-transparent pixels. | |
for y in 0..<height { | |
for x in 0..<width { | |
let pixelIndex = (width * y + x) * 4 /* 4 for A, R, G, B */ | |
if data[Int(pixelIndex)] != 0 { //Alpha value is not zero pixel is not transparent. | |
hasTransparentBackground = false | |
return hasTransparentBackground | |
} else { | |
hasTransparentBackground = true | |
return hasTransparentBackground | |
} | |
} | |
} | |
return hasTransparentBackground | |
} | |
private func createARGBBitmapContextFromImage(cgImage: CGImage) -> CGContext? { | |
let width = cgImage.width | |
let height = cgImage.height | |
let bitmapBytesPerRow = width * 4 | |
let bitmapByteCount = bitmapBytesPerRow * height | |
let colorSpace = CGColorSpaceCreateDeviceRGB() | |
/*if colorSpace == nil { | |
return nil | |
}*/ | |
let bitmapData = malloc(bitmapByteCount) | |
if bitmapData == nil { | |
return nil | |
} | |
let context = CGContext (data: bitmapData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bitmapBytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) | |
return context | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment