249
votes

Does anyone know how to convert a UIImage to a Base64 string, and then reverse it?

I have the below code; the original image before encoding is good, but I only get a blank image after I encode and decode it.

NSData *imageData = UIImagePNGRepresentation(viewImage);

NSString *b64EncStr = [self encode: imageData];

NSString *base64String = [self encodeBase64:imageData];
24
Try this: github.com/l4u/NSData-Base64user529758
Can anyone answer to this question: stackoverflow.com/questions/39657434/…user3011809

24 Answers

599
votes

Swift

First we need to have image's NSData

//Use image name from bundle to create NSData
let image : UIImage = UIImage(named:"imageNameHere")!
//Now use image to create into NSData format
let imageData:NSData = UIImagePNGRepresentation(image)!

//OR next possibility

//Use image's path to create NSData
let url:NSURL = NSURL(string : "urlHere")!
//Now use image to create into NSData format
let imageData:NSData = NSData.init(contentsOfURL: url)!

Swift 2.0 > Encoding

let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

Swift 2.0 > Decoding

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!

Swift 3.0 > Decoding

let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!

Encoding :

let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
print(strBase64)

Decoding :

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
print(decodedimage)
yourImageView.image = decodedimage

Swift 3.0

let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImageView.image = decodedimage

Objective-C

iOS7 > version

You can use NSData's base64EncodedStringWithOptions

Encoding :

- (NSString *)encodeToBase64String:(UIImage *)image {
 return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

Decoding :

- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
  NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
  return [UIImage imageWithData:data];
}

iOS 6.1 and < version

First Option : Use this link to encode and decode image

Add Base64 class in your project.

Encoding :

 NSData* data = UIImageJPEGRepresentation(yourImage, 1.0f);
 NSString *strEncoded = [Base64 encode:data];

Decoding :

 NSData* data = [Base64 decode:strEncoded ];;
 image.image = [UIImage imageWithData:data];

Another Option: Use QSUtilities for encoding and decoding


47
votes

Swift 5

Encoding

func convertImageToBase64String (img: UIImage) -> String {
    return img.jpegData(compressionQuality: 1)?.base64EncodedString() ?? ""
}

Decoding

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0))
    let image = UIImage(data: imageData!)
    return image!
}

Note: Tested in xcode 10.2

Swift 4

Encoding

func convertImageToBase64String (img: UIImage) -> String {
    let imageData:NSData = UIImageJPEGRepresentation(img, 0.50)! as NSData //UIImagePNGRepresentation(img)
    let imgString = imageData.base64EncodedString(options: .init(rawValue: 0))
    return imgString
}

Decoding

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0))
    let image = UIImage(data: imageData!)
    return image
}

Note: Tested in xcode 9.4.1

40
votes

Swift 4.2 Extension method

extension UIImage {
    func toBase64() -> String? {
        guard let imageData = self.pngData() else { return nil }
        return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
    }
}

XCode 9.1 and Swift 4.0

//
// Convert UIImage to a base64 representation
//
class func convertImageToBase64(image: UIImage) -> String {
    let imageData = UIImagePNGRepresentation(image)!
    return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
}

//
// Convert a base64 representation to a UIImage
//
class func convertBase64ToImage(imageString: String) -> UIImage {
    let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
    return UIImage(data: imageData)!
}
19
votes

SWIFT 3.0, XCODE 8.0

Replace String with your URL. and testImage is an outlet of ImageView

// Put Your Image URL
let url:NSURL = NSURL(string : "http://.jpg")!
// It Will turn Into Data
let imageData : NSData = NSData.init(contentsOf: url as URL)!
// Data Will Encode into Base64
let str64 = imageData.base64EncodedData(options: .lineLength64Characters)
// Now Base64 will Decode Here
let data: NSData = NSData(base64Encoded: str64 , options: .ignoreUnknownCharacters)!
// turn  Decoded String into Data
let dataImage = UIImage(data: data as Data)
// pass the data image to image View.:)
testImage.image = dataImage

Hope It Helps Thanks.

11
votes

Swift iOS8

// prgm mark ---- 

// convert images into base64 and keep them into string

func convertImageToBase64(image: UIImage) -> String {

    var imageData = UIImagePNGRepresentation(image)
    let base64String = imageData.base64EncodedStringWithOptions(.allZeros)

    return base64String

}// end convertImageToBase64


// prgm mark ----

// convert images into base64 and keep them into string

func convertBase64ToImage(base64String: String) -> UIImage {

    let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0) )

    var decodedimage = UIImage(data: decodedData!)

    return decodedimage!

}// end convertBase64ToImage
8
votes
@implementation UIImage (Extended)

- (NSString *)base64String {
    NSData * data = [UIImagePNGRepresentation(self) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return [NSString stringWithUTF8String:[data bytes]];
}

@end
8
votes

Swift 3.0

To convert image to base64 string

Tested in playground

    var logo = UIImage(named: "image_logo")
    let imageData:Data =  UIImagePNGRepresentation(logo)
    let base64String = imageData.base64EncodedString()
    print(base64String)
7
votes

In swift 2.0 use this extension (credit to Jonas Franz)

extension UIImage{
  func toBase64() -> String{
    let imageData = UIImagePNGRepresentation(self)!
    return imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
  }
}
5
votes

In Swift 3.0 and Xcode 8.0

Encoding :

let userImage:UIImage = UIImage(named: "Your-Image_name")!
let imageData:NSData = UIImagePNGRepresentation(userImage)! as NSData
let dataImage = imageData.base64EncodedString(options: .lineLength64Characters)

Decoding :

let imageData = dataImage
let dataDecode:NSData = NSData(base64Encoded: imageData!, options:.ignoreUnknownCharacters)!
let avatarImage:UIImage = UIImage(data: dataDecode as Data)!
yourImageView.image = avatarImage
4
votes

Swift-Extension:

extension UIImage{
     func toBase64() -> String{
          var imageData = UIImagePNGRepresentation(self)
          return imageData.base64EncodedStringWithOptions(.allZeros)
     }
}
4
votes

Swift 4

enum ImageFormat {
    case png
    case jpeg(CGFloat)
}

extension UIImage {
    func base64(format: ImageFormat) -> String? {
        var imageData: Data?

        switch format {
        case .png: imageData = UIImagePNGRepresentation(self)
        case .jpeg(let compression): imageData = UIImageJPEGRepresentation(self, compression)
        }

        return imageData?.base64EncodedString()
    }
}

extension String {
    func imageFromBase64() -> UIImage? {
        guard let data = Data(base64Encoded: self) else { return nil }

        return UIImage(data: data)
    }
}
3
votes

Swift 5.

class ImageConverter {

    func base64ToImage(_ base64String: String) -> UIImage? {
        guard let imageData = Data(base64Encoded: base64String) else { return nil }
        return UIImage(data: imageData)
    }

    func imageToBase64(_ image: UIImage) -> String? {
        return image.jpegData(compressionQuality: 1)?.base64EncodedString()
    }

}
3
votes

For the Base64 code like:

"data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAAB9klEQVR42u2YQYorMQxEBbqWQFc36FoG/6pyOpNZ/J20mGGaTiftF2hbLpWU2PnfYX/k55Jl5vhUVTu8luUdaCeFcydejjdwDUyQ5XV2JOcSZnkHZgiejusK51QGycrl2yIR1BwjjKivSFz8YC7fY91GKIj6PL5pp4/wWL54t3MHt/AjFxoJwmkYwosbh6/UEHE817hvi/vGex8gEkTdVRo1/55BM7kjUIgpoMW1DxB6kD+GtCX4PUFws40OwcUm0/lRYjOB3pG9YcguBFQuO0ISJ9UIrUP5CKy/MriXHDkETYmLDax1+RkgWBglQgUyq6T/HCAHBq7iJHd9KWWAlIKoGpiLc6HNDhDkETNYwqeVhym72snKKxA6BJL4UPM5QPYtgGwZeNZ5O0UvgSb0VGdcmVfJCQwQrM+pRiGnYJ497SUlv2NOYfOCX3qU2Equ7W3JAslsN7oDBDWWojcZq+KbEwQRdRYl1wD3ML52rpGc6w24qCXaKh4DRHWJbUPemqtEGyBMKC4Q/QmWiDWzRxkgO1UtSLh3svMaILeDpEGwrwvZ4Bkg9LynK1Y1LJWQdqKGnm3K7VTCz7vS9hIuUyYRd/xKcYRIHGqAViisQ4S/Uozmqo41Pn6bNRI1xS/fk2fMEKpDZYkpjP6B1T0HyN9/Nb+M/AORXDdE4Lb/mQAAAABJRU5ErkJggg=="

Use Swift5.0 code like:

func imageFromBase64(_ base64: String) -> UIImage? {
    if let url = URL(string: base64) {
        if let data = try? Data(contentsOf: url) {
            return UIImage(data: data)
        }
    }
    return nil
}
2
votes

Swift version - create base64 for image

In my opinion Implicitly Unwrapped Optional in case of UIImagePNGRepresenatation() is not safe, so I recommend to use extension like below:

extension UIImage {

    func toBase64() -> String? {
        let imageData = UIImagePNGRepresentation(self)
        return imageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
    }
}
2
votes

I tried all the solutions, none worked for me (using Swift 4), this is the solution that worked for me, if anyone in future faces the same problem.

let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options: 
 .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)

yourImage.image = decodedimage
2
votes

It's a very good to understand do you pass prefix as Tyler Sheaffer told. But for some reason you may need this prefix that describe the mime-type in the beginning of the base64 string, so I suggest this piece of code to pass some options before encoding (Swift 5):

extension UIImage {

    enum Format: String {
        case png = "png"
        case jpeg = "jpeg"
    }

    func toBase64(type: Format = .jpeg, quality: CGFloat = 1, addMimePrefix: Bool = false) -> String? {
        let imageData: Data?
        switch type {
        case .jpeg: imageData = jpegData(compressionQuality: quality)
        case .png:  imageData = pngData()
        }
        guard let data = imageData else { return nil }

        let base64 = data.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)

        var result = base64
        if addMimePrefix {
            let prefix = "data:image/\(type.rawValue);base64,"
            result = prefix + base64
        }
        return result
    }
}
2
votes

Decoding using convenience initialiser - Swift 5

extension UIImage {
    convenience init?(base64String: String) {
        guard let data = Data(base64Encoded: base64String) else { return nil }
        self.init(data: data)
    }
} 
1
votes
See my class -  AppExtension.swift


// MARK: - UIImage (Base64 Encoding)

public enum ImageFormat {
    case PNG
    case JPEG(CGFloat)
}

extension UIImage {

    public func base64(format: ImageFormat) -> String {
        var imageData: NSData
        switch format {
        case .PNG: imageData = UIImagePNGRepresentation(self)
        case .JPEG(let compression): imageData = UIImageJPEGRepresentation(self, compression)
        }
        return imageData.base64EncodedStringWithOptions(.allZeros)
    }
}
1
votes

In Swift 3.0

func decodeBase64(toImage strEncodeData: String) -> UIImage {

    let dataDecoded  = NSData(base64Encoded: strEncodeData, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!
    let image = UIImage(data: dataDecoded as Data)
    return image!

}
1
votes

Swift 4.2 | Xcode 10

extension UIImage {

    /// EZSE: Returns base64 string
    public var base64: String {
        return self.jpegData(compressionQuality: 1.0)!.base64EncodedString()
    }
}
1
votes

Swift 5, Xcode 10.

 let imageData = UIImage(named:"imagename").pngData()?.base64EncodedString(options: .lineLength64Characters)

print(imageData)
1
votes
//convert Image to Base64 (Encoding)

let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)

print(strBase64)

// convert Base64 to Image (Decoding)

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!

let decodedimage:UIImage = UIImage(data: dataDecoded)!

print(decodedimage)

yourImageView.image = decodedimage
0
votes

For iOS 7+, Objective-C, here's how to make the conversion starting with an image URL:

NSURL *url = [NSURL URLWithString:self.groove.thumbnailURL];

UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

NSString *base64String = [UIImagePNGRepresentation(image)
base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
0
votes

Swift 3.0 and Xcode 8.0

let imageData = UIImageJPEGRepresentation(imageView.image!, 1)

    let base64String = (imageData! as Data).base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
    print(base64String)