3

I'm trying to convert an Image object to Base64 and then send it to a server using HTTP request.

Note: ImageUIImage

This is my code:

struct MyView: View { 
    @State var image:Image? = nil // I want to convert this Image to Base64 when a button is clicked

    var body: some View {
        Button(action: {
            // ...
        }) {
            Image(systemName: "paperplane.fill")
        }
    }
}
J. Raji
  • 143
  • 4
  • 14
  • 1
    You say: “Note: Image ≠ UIImage”. True, but a SwiftUI Image isn’t anything of use. If you want to do something with the data, you need a UIImage. Just say `UIImage(systemName: "paperplane.fill")!` and away you go. – matt Nov 29 '19 at 02:43
  • But, I want to convert my variable 'image' to Base 64. – J. Raji Dec 11 '19 at 13:25
  • "and away you go". Unless you're using a platform that doesn't support UIImage, like macOS. – Drew Jan 10 '23 at 20:37

2 Answers2

-1
   func convertImageToBase64(image: UIImage) -> String? {
    let imageData = image.jpegData(compressionQuality: 1)
    return imageData?.base64EncodedString(options: 
    Data.Base64EncodingOptions.lineLength64Characters)
   }
-2
 func convertImageToBase64(_ image: UIImage) -> String {
    let imageData: NSData = UIImageJPEGRepresentation(image, 0.7)! as NSData
    let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)

    return strBase64
 }

I hope it will help you.

Flexicoder
  • 8,251
  • 4
  • 42
  • 56