Skip to content

Instantly share code, notes, and snippets.

@BrentMifsud
Last active July 14, 2024 12:50
Show Gist options
  • Save BrentMifsud/dce3fc6a76b8ef519ea7be0a3b050674 to your computer and use it in GitHub Desktop.
Save BrentMifsud/dce3fc6a76b8ef519ea7be0a3b050674 to your computer and use it in GitHub Desktop.
SwiftUI Image from data
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