Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI decoding image from String(Base64)

I have an image in the string (base 64) how I can decode this string for Image() using SwiftUI.

Know I am using this format:

Image(imageFromAppGroup(key: "image0")).resizable().frame(width: 70, height: 70)
                            .cornerRadius(10)
                            .background(Color(red: 0.218, green: 0.215, blue: 0.25))

I need a past base 64 images instead of "image0". How I can do this?

like image 678
Ice Avatar asked Mar 13 '26 08:03

Ice


1 Answers

You can use a UIImage for this:

let str = "IMAGE"
Image(uiImage: UIImage(data: Data(base64Encoded: str)!)!)

You will not want to force unwrap with ! here, so you should handle that too:

let str = "IMAGE"

if let data = Data(base64Encoded: str), let uiImage = UIImage(data: data) {
    Image(uiImage: uiImage)
} else {
    let _ = print("FAIL")
}

You could also create an Image extension:

extension Image {
    init?(base64String: String) {
        guard let data = Data(base64Encoded: base64String) else { return nil }
        guard let uiImage = UIImage(data: data) else { return nil }
        self = Image(uiImage: uiImage)
    }
}

/* ... */

var body: some View {
    Image(base64String: str)
}
like image 91
George Avatar answered Mar 15 '26 21:03

George