Skip to content

Instantly share code, notes, and snippets.

@BrentMifsud
Last active March 14, 2024 16:19
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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