270

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];
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
changey
  • 18,606
  • 9
  • 28
  • 34
  • Try this: https://github.com/l4u/NSData-Base64/ –  Jun 28 '12 at 19:15
  • Can anyone answer to this question: http://stackoverflow.com/questions/39657434/issue-in-coverting-zlib-compressed-base-64-string-to-uiimage/39659390?noredirect=1#comment66621861_39659390 – user3011809 Sep 23 '16 at 12:05

24 Answers24

615

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


Community
  • 1
  • 1
Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
  • Thanks, but how I can encode the image with that link? I didn't see a method that takes in NSData. There's only one that decodes the string. Thanks! – changey Jun 28 '12 at 19:31
  • add base64 class in your project and use its methods – Paresh Navadiya Jun 28 '12 at 19:36
  • 1
    @Safecase I wasn't the person that voted you down, but possibly the double post is the offence? – Tommy Jun 28 '12 at 20:05
  • 1
    It is not that but i wanted to give right answer to the question – Paresh Navadiya Jun 28 '12 at 20:07
  • 2
    `Base64` Class sleeps forever, I always force quite xcode if I use this even after making the image quality to 0.001f – shebelaw Jan 10 '13 at 00:15
  • @shebelaw: are you using ARC? if so, remove the `autoRelease` call in `Base64.m`. – Robert Jul 02 '13 at 15:31
  • @Prince: Bit late in the day, I know, but thanks for this. saved me a major headache. – Robert Jul 02 '13 at 16:05
  • In the first option, `[Base64 initialize]` should not be called. This gets called automatically upon class initialization: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/clm/NSObject/initialize – Barum Rho Jan 30 '14 at 21:56
  • This no longer works: `var url:NSURL = NSURL(string : "urlHere")! var imageData:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil)` Use `var imageData:NSData = NSData(contentsOfMappedFile: "urlHere")` instead. – Alexander Volkov Feb 07 '15 at 04:53
  • EDIT: `var imageData:NSData = NSFileManager.defaultManager().contentsAtPath("urlHere")` – Alexander Volkov Feb 07 '15 at 06:15
  • 1
    NSData(contentsOfURL: url, options: nil, error: nil) is what you should use now for Swift – quemeful Feb 24 '15 at 14:22
  • @E. Spiroux : Your suggestion has been added in answer. Thank you very much. – Paresh Navadiya Feb 15 '16 at 05:20
  • Would also be helpful to add @quemeful suggestion as the current code doesn't compile in Swift 2.x – Crashalot May 03 '16 at 23:35
  • 1
    @Crashalot : Have done changes please let me know if there is any other changes – Paresh Navadiya May 09 '16 at 09:55
  • when i do the encoding , it takes some time , is this normal or is there anyway that i can avoid this ?? – Mr.G Jul 27 '16 at 09:50
  • wish there was a concrete example on how to post multipart form with png using alamofire. – Cmag Nov 20 '16 at 04:07
  • 7
    Important note: make sure your base64 string doesn't include the prefix required on a browser to display, e.g. `data:image/jpeg;base64,` – Tyler Sheaffer Jan 10 '17 at 22:15
  • 2
    @TylerSheaffer I think this is an important message, which should be included in the answer. – Timeless Mar 16 '17 at 07:48
  • For new versions of swift, this : `//Now use image to create into NSData format let imageData:NSData = UIImagePNGRepresentation(image)!` have to be replaced by : `let imageData = UIImage.pngData(image!)` – Pablo Blanco Feb 28 '19 at 14:27
  • I get a nil value upon conversion, can't understand where it is going wrong – Arjun Oct 21 '20 at 08:35
85

Swift 5

Encoding

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

Decoding

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data(base64Encoded: imageBase64String)
    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

Michal Šrůtek
  • 1,647
  • 16
  • 17
Vivek
  • 4,916
  • 35
  • 40
  • Thank you for comment on my answer, Can you please up vote my answer, this is very helpful for me. – Vivek Sep 27 '18 at 14:17
42

Swift 4.2 Extension method

extension UIImage {
    func toBase64() -> String? {
        guard let imageData = self.pngData() else { return nil }
        return imageData.base64EncodedString(options: .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)!
}
Michal Šrůtek
  • 1,647
  • 16
  • 17
Soufiane ROCHDI
  • 1,543
  • 17
  • 24
  • 1
    This is not good. You shouldn't force unwrap image, as it would result in crashing of app if it fails to get image from data. You should unwrap last line like this "return UIImage(data: imageData) ?? UIImage()" – Vladimir Sukanica Dec 08 '21 at 14:01
  • Force unwrap is not good practice, I propose: func convertBase64StringToImage(imageBase64String:String) -> UIImage? { guard let imageData = Data(base64Encoded: imageBase64String) else { return nil } let image = UIImage(data: imageData) return image } – Medhi Aug 09 '23 at 10:01
20

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.

Naresh Reddy M
  • 1,096
  • 1
  • 10
  • 27
Avinash Mishra
  • 221
  • 2
  • 5
11

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
Vinod Joshi
  • 7,696
  • 1
  • 50
  • 51
8
@implementation UIImage (Extended)

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

@end
Peter Lapisu
  • 19,915
  • 16
  • 123
  • 179
8

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)
dimohamdy
  • 2,917
  • 30
  • 28
7

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

extension UIImage{
  func toBase64() -> String{
    let imageData = UIImagePNGRepresentation(self)!
    return imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
  }
}
Ciprian Rarau
  • 3,040
  • 1
  • 30
  • 27
6

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), let data = try? Data(contentsOf: url) {
        return UIImage(data: data)
    }
    return nil
}
Michal Šrůtek
  • 1,647
  • 16
  • 17
Yun CHEN
  • 6,450
  • 3
  • 30
  • 33
5

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
M.Nadeeshan
  • 251
  • 4
  • 8
4

Swift-Extension:

extension UIImage{
     func toBase64() -> String{
          var imageData = UIImagePNGRepresentation(self)
          return imageData.base64EncodedStringWithOptions(.allZeros)
     }
}
Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
Jonas Franz
  • 555
  • 1
  • 8
  • 18
  • For Swift 2.2, .allZeros didn't compile. So I used return imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) – Carl Smith Jun 07 '16 at 01:24
  • Use Encoding64CharacterLineLength instead of allZero – Jonas Franz Jun 07 '16 at 04:56
  • 1
    im using switft3, unable to convert to send to server: `let imageData = UIImagePNGRepresentation(ImageView.image!); let strBase64:String = imageData!.base64EncodedString()` – Cmag Nov 20 '16 at 04:05
  • @Cmag I know your comment is 2 years old but did you manage to fix it? – Zun Nov 27 '18 at 07:57
  • @ZUNJAE am afraid i dont recall how i fixed it, dont have access to the solution any more – Cmag Dec 03 '18 at 05:53
4

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)
    }
}
oscarr
  • 529
  • 5
  • 6
4

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()
    }

}
atereshkov
  • 4,311
  • 1
  • 38
  • 49
3

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
Zubair
  • 915
  • 2
  • 9
  • 28
2

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)
    }
}
lukszar
  • 1,252
  • 10
  • 13
2

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
    }
}
eli7ah
  • 355
  • 2
  • 10
2

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)
    }
} 
Benny Davidovitz
  • 1,152
  • 15
  • 18
1
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)
    }
}
Alvin George
  • 14,148
  • 92
  • 64
1

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!

}
Maniganda saravanan
  • 2,188
  • 1
  • 19
  • 35
1

Swift 4.2 | Xcode 10

extension UIImage {

    /// EZSE: Returns base64 string
    public var base64: String {
        return self.jpegData(compressionQuality: 1.0)!.base64EncodedString()
    }
}
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
1

Swift 5, Xcode 10.

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

print(imageData)
Kedar Sukerkar
  • 1,410
  • 1
  • 16
  • 22
1
//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
Izaak van Dongen
  • 2,450
  • 13
  • 23
Miral Kamani
  • 11
  • 1
  • 3
0

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];
Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
snibbe
  • 2,715
  • 1
  • 27
  • 34
0

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)
Amit Verma
  • 1,393
  • 1
  • 8
  • 7