Converting Image to BASE64 String in swift

不羁的心 提交于 2019-12-05 08:46:26

Actually it is not taking time to convert(very less time) for printing it will take more time so don't print it....

Yogendra Girase

You can apply this code

let imageData: Data? = UIImageJPEGRepresentation(getImage(), 0.4)
let imageStr = imageData?.base64EncodedString(options: .lineLength64Characters) ?? ""
print(strBase64)

Swift 4 version. This simple func worked well for me. Confirmed decoded image back using this: https://codebeautify.org/base64-to-image-converter Hope this helps someone.

public static func  convertImageToBase64String(image : UIImage ) -> String 
{
    let strBase64 =  image.pngData()?.base64EncodedString()
    return strBase64!
}

Make sure your image extension first.

// .png

    guard let imageData = UIImagePNGRepresentation(UIImage) else {
        return ""
    }

// .JPEG

   guard let imageData = UIImageJPEGRepresentation(UIImage, 1) else {
                return ""
    }

// BASE 64

  imageData.base64EncodedString()
let imageData: Data? = UIImageJPEGRepresentation(YourImage, 0.4)
let imageStr = imageData?.base64EncodedString(options: .lineLength64Characters) ?? ""
print(imageStr,"imageString")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!