Mrugesh Tank
Mrugesh Tank

Reputation: 3560

Getting wrong Base64 for image in Swift4

I want to generate Base64 string for a specific image. for that I've wrote below code

let imageData = UIImagePNGRepresentation(imgProfile.image!)!
var imageStr = imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)

and I'm getting this output string as Base64 which is not decoded (i.e. wrong).

but when I'm generating Base64 from here, I'm getting this output string, which is successfully decoded and getting the image back (i.e. correct)

Please help me to find the issue.
Thanks in advance

I've already visited following threads.
1. https://stackoverflow.com/a/47610733/3110026
2. https://stackoverflow.com/a/46309421/3110026

Upvotes: 1

Views: 2271

Answers (3)

iOSDev456
iOSDev456

Reputation: 11

Additional, I was getting the same problem, but for me \r\n was not the issue, when i get the base64 string from server there were blank spaces between some characters and after comparing it with correct Base64 string what i found is that i have to add "+" sign in blank spaces. When I did that...Bingooooo...... "yourBase64String" can contain \r\n..

if let cleanImageString =  yourBase64String.replacingOccurrences(of: " ", with: "+") {
        if let data = Data(base64Encoded: cleanImageString, options: .ignoreUnknownCharacters) {
            yourImageView.image = UIImage(data: data)
        }
    }

Upvotes: 1

vadian
vadian

Reputation: 285072

The string is properly encoded. You are adding CRLF (\n\r) after each 64 characters with the options you passed.

The simplest solution is to pass no options

let imageData = UIImagePNGRepresentation(imgProfile.image!)!
let imageStr = imageData.base64EncodedString()

Or decode the data with options ignoreUnknownCharacters

let imageData = UIImagePNGRepresentation(imgProfile.image!)!
let imageStr = imageData.base64EncodedString(options: .lineLength64Characters)
...
if let data = Data(base64Encoded: imageStr, options: .ignoreUnknownCharacters) { ...

Upvotes: 0

Moayad Al kouz
Moayad Al kouz

Reputation: 1392

try below UIImage extension:

extension UIImage {



    /// Encoded Base64 String of the image
    var base64: String? {
        guard let imageData = UIImageJPEGRepresentation(self, 1.0) as NSData? else {
            print("Error occured while encoding image to base64. In \(self), \(#function)")
            return nil
        }
        return imageData.base64EncodedString()
    }


}

Upvotes: 0

Related Questions