Last active
July 14, 2024 12:50
-
-
Save BrentMifsud/dce3fc6a76b8ef519ea7be0a3b050674 to your computer and use it in GitHub Desktop.
SwiftUI Image from data
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
import Foundation | |
import SwiftUI | |
#if canImport(UIKit) | |
import UIKit | |
#elseif canImport(AppKit) | |
import AppKit | |
#endif | |
extension Image { | |
/// Initializes a SwiftUI `Image` from data. | |
init?(data: Data) { | |
#if canImport(UIKit) | |
if let uiImage = UIImage(data: data) { | |
self.init(uiImage: uiImage) | |
} else { | |
return nil | |
} | |
#elseif canImport(AppKit) | |
if let nsImage = NSImage(data: data) { | |
self.init(nsImage: nsImage) | |
} else { | |
return nil | |
} | |
#else | |
return nil | |
#endif | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment