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, bu
In swift 2.0 use this extension (credit to Jonas Franz)
extension UIImage{
func toBase64() -> String{
let imageData = UIImagePNGRepresentation(self)!
return imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
}
}
let userImage:UIImage = UIImage(named: "Your-Image_name")!
let imageData:NSData = UIImagePNGRepresentation(userImage)! as NSData
let dataImage = imageData.base64EncodedString(options: .lineLength64Characters)
let imageData = dataImage
let dataDecode:NSData = NSData(base64Encoded: imageData!, options:.ignoreUnknownCharacters)!
let avatarImage:UIImage = UIImage(data: dataDecode as Data)!
yourImageView.image = avatarImage
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.
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];
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)
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
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