Skip to content

Instantly share code, notes, and snippets.

@mishimay
Created July 7, 2019 01:35
Show Gist options
  • Save mishimay/7b65167cf829e022f46dfa749d018661 to your computer and use it in GitHub Desktop.
Save mishimay/7b65167cf829e022f46dfa749d018661 to your computer and use it in GitHub Desktop.
Remove alpha channel from png using Swift
// Usage: swift remove_alpha_channel.swift filename.png
import Foundation
import CoreImage
let arguments = CommandLine.arguments
let filename = arguments[1]
let dataProvider = CGDataProvider(filename: filename)!
let cgImage = CGImage(pngDataProviderSource: dataProvider, decode: nil, shouldInterpolate: true, intent: .defaultIntent)!
let context = CGContext(data: nil, width: cgImage.width, height: cgImage.height, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: cgImage.bytesPerRow, space: cgImage.colorSpace!, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: context.width, height: context.height))
let destination = CGImageDestinationCreateWithURL(URL(fileURLWithPath: filename) as CFURL, "public.png" as CFString, 1, nil)!
CGImageDestinationAddImage(destination, context.makeImage()!, nil)
CGImageDestinationFinalize(destination)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment