Skip to content

Instantly share code, notes, and snippets.

@bubudrc
Forked from BrentMifsud/Image+Data.swift
Created January 30, 2023 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bubudrc/c00e3e6060854c74bb46e87bd0f6281a to your computer and use it in GitHub Desktop.
Save bubudrc/c00e3e6060854c74bb46e87bd0f6281a 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