Convert Image to Base64 string in iOS
Swift
//create image instance //with image name from bundle var image : UIImage = UIImage(named:"imageNameHere") var imageData = UIImagePNGRepresentation(image) //OR with path var url:NSURL = NSURL.URLWithString("urlHere") var imageData:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil)
Encoding
let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!) println(base64String)
Decoding
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.fromRaw(0)!) var decodedimage = UIImage(data: decodedData) println(decodedimage) yourImageView.image = decodedimage as UIImage
iOS7 > Objectice-C version
You can use NSData’s base64EncodedStringWithOptions
Now encode as:
- (NSString *)encodeToBase64String:(UIImage *)image { return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; }
Decode as:
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData { NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters]; return [UIImage imageWithData:data]; }