By changey


2012-06-28 19:11:10 8 Comments

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];

19 comments

@Kedar Sukerkar 2018-12-13 08:45:00

Swift 4.2, Xcode 10.1

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

print(imageData)

@Souf R 2017-12-02 17:48:30

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

@oscarr 2018-11-21 20:00:04

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

@Ashish Kakkad 2018-10-05 13:03:58

Swift 4.2 | Xcode 10

extension UIImage {

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

@Zubair 2018-07-19 15:51:36

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

@Vivek 2018-07-18 05:55:14

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

@Masum Biswas 2018-09-27 11:16:12

now wrong swift 4

@Vivek 2018-09-27 14:17:56

Thank you for comment on my answer, Can you please up vote my answer, this is very helpful for me.

@Paresh Navadiya 2012-06-28 19:22:03

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


@changey 2012-06-28 19:31:53

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!

@Paresh Navadiya 2012-06-28 19:36:21

add base64 class in your project and use its methods

@Paresh Navadiya 2012-06-28 19:37:58

-1 vote down for what

@Tommy 2012-06-28 20:05:53

@Safecase I wasn't the person that voted you down, but possibly the double post is the offence?

@Paresh Navadiya 2012-06-28 20:07:24

It is not that but i wanted to give right answer to the question

@changey 2012-06-28 23:55:27

@Safecase Thanks=)

@shebelaw 2013-01-10 00:15:31

Base64 Class sleeps forever, I always force quite xcode if I use this even after making the image quality to 0.001f

@Robert 2013-07-02 15:31:42

@shebelaw: are you using ARC? if so, remove the autoRelease call in Base64.m.

@Robert 2013-07-02 16:05:09

@Prince: Bit late in the day, I know, but thanks for this. saved me a major headache.

@Barum Rho 2014-01-30 21:56:41

In the first option, [Base64 initialize] should not be called. This gets called automatically upon class initialization: developer.apple.com/library/mac/documentation/Cocoa/Referenc‌​e/…

@Alexander Volkov 2015-02-07 04:53:36

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 2015-02-07 06:15:37

EDIT: var imageData:NSData = NSFileManager.defaultManager().contentsAtPath("urlHere")

@quemeful 2015-02-24 14:22:34

NSData(contentsOfURL: url, options: nil, error: nil) is what you should use now for Swift

@Paresh Navadiya 2016-02-15 05:20:46

@E. Spiroux : Your suggestion has been added in answer. Thank you very much.

@Crashalot 2016-05-03 23:35:33

Would also be helpful to add @quemeful suggestion as the current code doesn't compile in Swift 2.x

@Paresh Navadiya 2016-05-09 09:55:21

@Crashalot : Have done changes please let me know if there is any other changes

@Mr.G 2016-07-27 09:50:35

when i do the encoding , it takes some time , is this normal or is there anyway that i can avoid this ??

@Cmag 2016-11-20 04:07:15

wish there was a concrete example on how to post multipart form with png using alamofire.

@Tyler Sheaffer 2017-01-10 22:15:04

Important note: make sure your base64 string doesn't include the prefix required on a browser to display, e.g. data:image/jpeg;base64,

@Timeless 2017-03-16 07:48:47

@TylerSheaffer I think this is an important message, which should be included in the answer.

@AppHero2 2017-12-15 07:11:36

thank you guys!

@Avinash Mishra 2016-10-19 06:16:18

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.

@dimo hamdy 2017-01-22 14:14:49

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)

@Amit Verma 2017-01-09 11:20:55

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)

@M.Nadeeshan 2016-12-15 06:37:10

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

@Mc.Lover 2016-12-19 08:05:44

Great thank you

@ggnoredo 2018-02-06 11:41:24

i can't thank you enough

@Maniganda saravanan 2016-10-19 14:01:59

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!

}

@lukszar 2016-09-07 13:46:41

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

@Ciprian Rarau 2015-10-23 17:33:23

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

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

@A.G 2015-10-13 08:47:27

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

@Jonas Franz 2015-07-02 15:38:11

Swift-Extension:

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

@Carl Smith 2016-06-07 01:24:47

For Swift 2.2, .allZeros didn't compile. So I used return imageData.base64EncodedStringWithOptions(NSDataBase64Encodin‌​gOptions(rawValue: 0))

@Jonas Franz 2016-06-07 04:56:30

Use Encoding64CharacterLineLength instead of allZero

@Cmag 2016-11-20 04:05:55

im using switft3, unable to convert to send to server: let imageData = UIImagePNGRepresentation(ImageView.image!); let strBase64:String = imageData!.base64EncodedString()

@ZUNJAE 2018-11-27 07:57:20

@Cmag I know your comment is 2 years old but did you manage to fix it?

@Cmag 2018-12-03 05:53:42

@ZUNJAE am afraid i dont recall how i fixed it, dont have access to the solution any more

@snibbe 2014-12-24 00:50:48

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];

@Vinod Joshi 2015-02-10 11:01:52

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

@Peter Lapisu 2013-10-02 15:17:16

@implementation UIImage (Extended)

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

@end

@Myxtic 2014-12-18 19:27:52

Simple and elegant. Love it!

Related Questions

Sponsored Content

27 Answered Questions

[SOLVED] What's the difference between the atomic and nonatomic attributes?

23 Answered Questions

[SOLVED] How can you encode a string to Base64 in JavaScript?

  • 2008-10-29 13:34:18
  • username
  • 887187 View
  • 668 Score
  • 23 Answer
  • Tags:   javascript base64

3 Answered Questions

[SOLVED] How to convert a base64String to String in Swift?

  • 2015-08-06 14:59:34
  • Sakthimuthiah
  • 14639 View
  • 7 Score
  • 3 Answer
  • Tags:   swift base64

9 Answered Questions

[SOLVED] Base 64 encode and decode example code

  • 2011-09-09 10:38:57
  • max
  • 240867 View
  • 173 Score
  • 9 Answer
  • Tags:   java android base64

4 Answered Questions

[SOLVED] How do I encode and decode a base64 string?

  • 2012-07-31 15:06:24
  • Kevin Driedger
  • 586414 View
  • 684 Score
  • 4 Answer
  • Tags:   c# base64

2 Answered Questions

[SOLVED] Convert UIImage to base64 string in swift

2 Answered Questions

[SOLVED] Converting a Base64 String into a UIImage

2 Answered Questions

[SOLVED] How to disable or bypass escape sequence in iOS string for Base64 Image url data

1 Answered Questions

[SOLVED] MKMapView -> to UIImage -> to NSData

2 Answered Questions

[SOLVED] UIImage Base64 encoding fails

Sponsored Content