Skip to content

Instantly share code, notes, and snippets.

@ThinhPhan
Last active July 22, 2023 07:16
Show Gist options
  • Save ThinhPhan/c3ec64d31a4c674f7dd9 to your computer and use it in GitHub Desktop.
Save ThinhPhan/c3ec64d31a4c674f7dd9 to your computer and use it in GitHub Desktop.
Convert Image to Base64 string
// Ref: http://stackoverflow.com/questions/11251340/convert-image-to-base64-string-in-ios-swift
// iOS7 > version for Objective-C
// 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];
}
// iOS 6.1>
// First Option : Use this link[http://www.imthi.com/blog/programming/iphone-sdk-base64-encode-decode.php] to encode and decode image
// Add Base64[http://www.imthi.com/wp-content/uploads/2010/08/base64.zip] class in your project. Now encode as:
NSData* data = UIImageJPEGRepresentation(yourImage, 1.0f);
NSString *strEncoded = [Base64 encode:data];
// Decode as:
NSData* data = [Base64 decode:strEncoded ];;
image.image = [UIImage imageWithData:data];
// Another Option: Use QSUtilities[https://github.com/mikeho/QSUtilities/blob/master/QSStrings.h] for encoding and decoding
//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(string : "urlHere")!
var imageData:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil)
// Encoding
let base64String = imageData.base64EncodedStringWithOptions(.allZeros)
println(base64String)
// Decoding
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.fromRaw(0)!)
var decodedimage = UIImage(data: decodedData)
println(decodedimage)
yourImageView.image = decodedimage as UIImage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment