Base64 encoding with Swift 3 - ios

How do you encode an image to base64 in Swift 3.0?
I tried to do it this way:
let imageData = UIImageJPEGRepresentation(globalImage!, 75)
let string64 = imageData!.base64EncodedString()
where globalImage is my image. I successfully sent the data to my web server but when I try to load the image it's not in a form that my computer can recognize.

Here are the encoding and decoding methods.
func encodeImageToBase64(image : UIImage) -> String{
let imageData : Data = UIImagePNGRepresentation(image)! as Data
let strBase64 = imageData.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
return strBase64
}
func decodeBase64ToImage(base64 : String) -> UIImage{
let dataDecoded : NSData = NSData(base64Encoded: base64, options: NSData.Base64DecodingOptions(rawValue: 0))!
let decodedimage : UIImage = UIImage(data: dataDecoded as Data)!
return decodedimage
}

Your second parameter is 75, it should be 0.7
let imageData = UIImageJPEGRepresentation(globalImage!, 0.7)

Related

How to Reduce the base64 String Length

I am trying to convert the Image selected from the UIImagePickerController into base64 String. But the length of the String is about more than 12 Corerit's making iPhone hang.
This is the code that I using.
func compressImage(img:UIImage) -> String {
Utill.showProgress()
var imageData = Data(UIImagePNGRepresentation(img)! )
print("***** Uncompressed Size \(imageData.description) **** ")
imageData = UIImageJPEGRepresentation(img, 0.025)!
print("***** Compressed Size \(imageData.description) **** ")
let image = UIImage(data: imageData)
let imagesData:NSData = UIImagePNGRepresentation(image!)! as NSData
let strBase64 = imagesData.base64EncodedString(options: .lineLength64Characters)
Utill.dismissProgress()
return strBase64
}
Is there any other way to reduce the String, to be around 10K - 30K?
Try this code,
func convertImageToBase64(image: UIImage)-> String {
if let imageData = image.jpegData(compressionQuality: 0.25){
let base64String = imageData.base64EncodedString()
return base64String
}
return ""
}

Convert Raw JSON response to image

I have a server response which is in json format and I have an image sent as a raw data in the response. I want to convert it into image and put it in the imageView that I have. The value for the image in json response is :
"storedisplayimage" : "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQy419TQ6bt9rpJqkugoopy9sQ3R2vzzOTjkMqK3mb
store what JSON throws you so you can displayed later while convert
override func viewDidLoad() {
super.viewDidLoad()
let userImage = UserDefaults.standard.string(forKey: "PictureFromJson")
let imageBase64 = ConduPerfilViewController.convertBase64ToImage(imageString: userImage!)
viewphoto.image = imageBase64
}
convert JSON base64 to IMG
//convert base64ToImage
class func convertBase64ToImage(imageString: String) -> UIImage {
let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
return UIImage(data: imageData)!
}

Decoding Base64 image in swift

I need to convert the image to/from Base64.
All working fine for JPG files, but if I upload PNG and then open it in the app it leads to the crash with error
"Unexpectedly found nil while unwrapping an Optional value"
while trying to create Data from the encoded string
Here is my code:
For Encoding:
static func base64Convert(base64String: String?) -> UIImage {
var decodedImage = #imageLiteral(resourceName: "no_prof_image")
if ((base64String?.isEmpty)! || (base64String?.contains("null"))!) {
return decodedImage
}else {
if let imageBase64String = base64String,
let dataDecoded = Data(base64Encoded: imageBase64String, options: .ignoreUnknownCharacters) {
decodedImage = UIImage(data: dataDecoded) ?? #imageLiteral(resourceName: "no_prof_image")
}
return decodedImage
}
}
For Decoding:
static func makeProfileBase64FromImage(image: UIImage) -> String? {
var imageData : Data?
if let jpegData = UIImageJPEGRepresentation(image, 1.0) {
imageData = jpegData
} else if let pngData = UIImagePNGRepresentation(image) {
imageData = pngData
}
return imageData?.base64EncodedString()
}
What I tried:
1) All encoding options
2) All decoding options
3) Swap UIImageJPEGRepresentation to UIImagePNGRepresentation. It leads to the same error but with jpg images.
UPDATE
Here is code how I send data to the server:
var imageToSend : String = "null"
if profileImage.image != #imageLiteral(resourceName: "no_prof_image"),
let validImage = profileImage.image,
let imageBase64 = AppUtils.makeProfileBase64FromImage(image: validImage) {
imageToSend = imageBase64
}
let parameters : Parameters = [
"image": imageToSend
]
Alamofire.request(AppUtils.API_URL + "update_profile.php", method: .post, parameters: parameters)
.validate().responseData() {response in
switch response.result {
case .success:
//...Some stuff
break
case .failure:
//...Some stuff
break
}
}
Part of the string that came to the server:
/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAABkKADAAQAAAABAAABkAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBkAGQAwERAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//E
UPDATED CODE IN THE QUESTION
For now, the code doesn't have force unwrap. But now I always gets standard #imageLiteral(resourceName: "no_prof_image"). (Before, at least jpg works fine :) )
Quite obviously, you use UIImageJPEGRepresentation for .jpeg images, but for .png images you should use UIImagePNGRepresentation
Also, don't use force unwrapping.
static func makeBase64FromImage(image: UIImage) -> String? {
var imageData : Data?
if let jpegData = UIImageJPEGRepresentation(image, 1.0) {
imageData = jpegData
} else if let pngData = UIImagePNGRepresentation(image) {
imageData = pngData
}
return imageData?.base64EncodedString()
}
Looks like your issue is your PNG data size which is much bigger than JPEG data. So your server might have a size limit for your image upload.
Regarding your encoding method The second condition else if let pngData = UIImagePNGRepresentation(image) will never be executed. You have to choose which one you would like to use PNG or JPEG data representations (JPEG most times due to the size limit). Btw this would be much easier using optional chaining.
return UIImageJPEGRepresentation(image, 1)?.base64EncodedString()
Swift 4.2 Xcode 10 or later
return image.jpegData(compressionQuality: 1)?.base64EncodedString()
As #mag_zbc suggested, start with:
static func makeBase64FromImage(image: UIImage) -> String? {
var imageData : Data?
if let jpegData = UIImageJPEGRepresentation(image, 1.0) {
imageData = jpegData
} else if let pngData = UIImagePNGRepresentation(image) {
imageData = pngData
}
return imageData?.base64EncodedString()
}
Then, update this code to:
var imageToSend : String = "null"
if profileImage.image != #imageLiteral(resourceName: "no_prof_image"),
let validImage = profileImage.image,
let imageBase64 = AppUtils.makeBase64FromImage(image: validImage) {
imageToSend = imageBase64
}
let parameters : Parameters = [
"image": imageToSend
]
...
In general, you want to avoid using "!" anywhere unless you can 100% confirm that in any and all cases the value will always be defined. In this case, I believe the issue was your code being called with profileImage.image == nil
A profileImage.image being nil would != to the image literal, and therefore would have entered the conditional if you defined. Then by forcing it to be unwrapped with "!" you tried to unwrap nil.
Good luck!

Decoding base64String into UIImage in Swift 2

I have a base64String that I need to convert into a UIImage() and display in a UIImageView. I've been trying for hours to convert it, but I keep getting nil from UIImage(data: data). When I print(data)it looks normal, but I can't decode it properly into an image. What's going on, and why is this code not working?
let base64String = "data:image/x-icon;base64,AAABAAEAEBAAAAAAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAQAQAAAAAAAAAAAAAAAAAAAAAAAA2Gin/Nhop/zYaKf82Gin/Nhop/zYaKf82Gin/Nhop/zYaKf82Gin/Nhop/zYaKf82Gin/Nhop/zYaKf82Gin/Nhop/zYaKf88IjD/XUlU/2RRW/9GLzv/kouQ/6Sdn/84Hiz/RCs4/0QrOP82Gyn/Nhop/0UtOv9FLDr/OR8t/zYaKf85Hyz/ubO2////////////7+/v//////+6tbb/RS47/+bl5v/Py87/OR4s/0gxPf/z8/P/vrq8/1dFTv82Gin/a1xk//////+4s7f/hnuB//b29v/+/v7/SjdC/0EoNv/5+Pn/39zg/zgdK/9oWGD//////5OIjf9ELTn/Nhop/6CYnP//////X0xW/zYaKf/Cvb///////0czPv9AJzX/9vX2/+Dc3/86Hy7/lIqP//////9jUlr/OB0s/zYaKf+qpKb//////2ZSXf82Gin/zcbJ//////9RPkf/QCc1//X19f/c2Nv/Pyc0/8nGyP/8/Pz/RzA8/zYaKf82Gin/q6Wn//////9kUVv/Nhop/83Gyf//////UD1G/0AnNf/19fX/1NDT/0w4RP/5+fn/zcnL/zkfLf82Gin/Nhop/6ulp///////ZFFb/zYaKf/Nxsn//////1A9Rv9AJzX/8fDx//n4+f/U0NP//////6GYnP82Gin/Nhop/zYaKf+rpaf//////2RRW/82Gin/zcbJ//////9QPUb/QCc0//Dv7///////+vr6///////39vf/RzM//zYbKf82Gin/q6Wn//////9kUVv/Nhop/83Gyf//////UD1G/0AnNP/19PT/4N3e/0s0QP+HfIL//////5uRlv9HLzv/Nhop/6ylp///////ZFFb/zYaKf/Nxsn//////1A9Rv9AJzT/9fX1/9zZ2v85Hiz/VD9K//////+7tLf/VkJM/zYaKf+po6X//////2RRW/82Gin/xb3C//////9OPEX/QCc0//b19f/c2tr/OR4s/1I9SP//////t7Gz/1M/SP82Gin/joWJ//////98b3b/Ri47/9XS1P//////STI+/0MpNv/y8fH/6+np/3FfaP+poab//////46Dif9CKjf/Nhop/0c0P//39vf///////r6+///////pp+k/zYaKf9GLjr/8O/v//////////////////Dv7/9AKjb/Nhop/zYaKf82Gin/UkBJ/7Osrv/DvsD/joSJ/zkhLv82Gin/PCIw/35wdv+GeH7/hHd8/39yef9HMT3/Nhop/zYaKf82Gin/Nhop/zYaKf82Gin/Nhop/zYaKf82Gin/Nhop/zYaKf82Gin/Nhop/zYaKf82Gin/Nhop/zYaKf82Gin/AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//w="
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
print(decodedData) // prints out fine
let image = UIImage(data: decodedData!) // keep getting nil here
use this function for decode Base64 String to String
public func decodebase64(str : String) -> String{
let decodedData = NSData(base64EncodedString: str, options:NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = String(data: decodedData!, encoding: NSUTF8StringEncoding)
return decodedString!}
then use this function in this way
let newimage:String? = decodebase64(busimage)
if (newimage?.characters.count != 0)
{
ImageLoader.sharedLoader.imageForUrl(newimage!) { (images, url) -> () in
if (images != nil)
{
cell.compnylogo.image = images!
}
}
}
here you have to just use. or drag and drop this swift file.
Use this image Loader File this will help you

NSDataBase64DecodingOptions always returns nil

There are a lot of similar questions but non of them helped me out so I just don't know what to do but ask. So this is how I encode a UIImage:
let data: NSData = UIImagePNGRepresentation(imageResized)!
let base64String: NSString = data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
and decoding (as suggested here):
if let range = base64.rangeOfString("data:image/png;base64,", options: .AnchoredSearch) {
base64.removeRange(range)
}
let decodedData = NSData(base64EncodedString: base64, options: NSDataBase64DecodingOptions(rawValue: 0))
if let decodedImage = UIImage(data: decodedData!) {
self.imageList.append(decodedImage)
}
But the app crashes when initializing decodedData and I can't figure out why.
I checked my base64 string here and it returns the picture.
Any help will be very appreciated!
Try with this:
if let decodedData = NSData(base64EncodedString: base64, options:NSDataBase64DecodingOptions.IgnoreUnknownCharacters){
if(decodedData.length > 0){
let imageDecodeData = UIImage(data: decodedData)!
}
else{
print("error")
}
}
Replace the line with let decodedData with:
let decodedData = NSData(base64EncodedString: base64, options: [])
And also make sure that your using correct variables:
// 1. This should be a variable if you're mutating it.
let base64String = data...
// 2. You should probably do this on your base64String
if let range = base64.rangeOfString(...)

Resources