Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion Sources/Pulse/Helpers/ImageProcessor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ enum Graphics {
}

static func encode(_ image: PlatformImage, compressionQuality: CGFloat = 0.8) -> Data? {
guard let source = image.cgImage else {
guard let source = image.removingAlphaChannel()?.cgImage else {
return nil
}
let data = NSMutableData()
Expand Down Expand Up @@ -100,3 +100,27 @@ extension NSImage {
}
}
#endif

extension PlatformImage {

func removingAlphaChannel() -> PlatformImage? {
guard let cgImage = self.cgImage else { return nil }
guard [.first, .last, .premultipliedFirst, .premultipliedLast].contains(cgImage.alphaInfo) else { return self }

let width = cgImage.width
let height = cgImage.height
let colorSpace = CGColorSpaceCreateDeviceRGB()

// Create a context with no alpha channel (noneSkipLast = RGBX)
let bitmapInfo = CGBitmapInfo.byteOrder32Big.union(CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue))

guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else {
return nil
}

context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
guard let newCGImage = context.makeImage() else { return nil }

return PlatformImage(cgImage: newCGImage)
}
}