UIImage view encode to base64 - ios

I'm trying to encode UIImage as base64 string. My code is this:
#IBOutlet weak var photoImageView: UIImageView!
let image : UIImage = UIImage(named:"photoImageView")!
let imageData:NSData = UIImagePNGRepresentation(image)!
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
the problem is that I get this kind of error : "fatal error: unexpectedly found nil while unwrapping an Optional value"
What am I doing wrong?

Prasad's comment is likely the issue you're running into.
For any functions that return optionals, I usually use if - let syntax or guards to make sure I don't accidentally unwrap a nil.
if let image = UIImage(named:"photoImageView") {
if let imageData = UIImagePNGRepresentation(image) {
// swift 2
// imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
// swift 3
let strBase64:String = imageData.base64EncodedString(options: [.lineLength64Characters])
} else {
print("can't get PNG representation")
}
} else {
print("can't find photoImageView image file")
}

#Enix your comment did the trick. Solution to my problem was this line
let image = photoImageView.image
As you have pointed out UIImage is initialised with image asset, not with an image view

Related

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!

how to load an image from the url getting from server

I am having and imageView and I am getting the userData from the server when loggedIn in the userData I have a parameter for "profilePic":"penguins.jpg". now I am adding the domain like "http://.....(self.userData.value(forKey: "profilePic")!)" and saving this value into a string variable to store and when I am accessing the value and trying to convert the url into data and adding to imageView.image it is throwing : unexpectedly found nil while unwrapping an optional value..
All my other userData like name,address,phoneNumber are showing fine except for Image.
My Code:
here are the some of the many ways I tried:
way:1
let ad : AppDelegate = UIApplication.shared.delegate as! AppDelegate
let imageUrlString = ad.userImagePath
let imageUrl:URL = URL(string: imageUrlString)! // it is throwing error here(: unexpectedly found nil while unwrapping an optional value)
DispatchQueue.global(qos: .userInitiated).async {
let imageData:NSData = NSData(contentsOf: imageUrl)!
DispatchQueue.main.async {
let image = UIImage(data: imageData as Data)
self.profileImage.image = image
}
}
way:2
if let url = NSURL(string: ad.userImagePath) {
if let data = NSData(contentsOf: url as URL){
if let imageUrl = UIImage(data: data as Data) {
profileImage.image = imageUrl
}
}
}
I have tried different ways to solve this, can't figure out what is my mistake.. finally I am here.. Please someone help he...

I want to encode and decode a UIImage to and from a String for a value in AEXML in swift

//To encode I found the following example. I don't know if it works yet
#IBAction func exitImageViewController(seque:UIStoryboardSegue){
let imageController = seque.destination as! MyImageViewController
let myView = imageController.imageView
imageData = UIImagePNGRepresentation((myView?.image!)!)
imageString = imageData?.base64EncodedString()
// Is this swift code correct?
//I cannot find an example of decoding String back to UIImage
The code you posted looks fine. To encode back you can do this:
let data = Data(base64Encoded: imageString!)
let img = UIImage(data: data!)

How can I upload images to Parse.com programatically?

I have a very large set of images to upload, and the best way to do that is to let my app do it for me. But after copy and pasting the code from Parse's docs, it doesn't work.
var image = NSData(contentsOfURL: NSURL(string: "XY1_EN_1.jpg")!)!
#IBAction func xyButton1(sender: AnyObject) {
for var i = 1; i < 147; i++ {
let imageData = UIImageJPEGRepresentation(image)
//ERROR on line above: Missing argument for parameter #2 in call
let imageFile = PFFile(name:"image.png", data:imageData)
var userPhoto = PFObject(className:"Cards")
userPhoto["imageName"] = "XY1_EN_1"
userPhoto["imageFile"] = imageFile
userPhoto.save()
}
}
What am I doing wrong?
There are two problems with the code. UIImageJPEGRepresentation(::) takes two parameters, a UIImage and a float. Right now you are calling UIImageJPEGRepresentation(_:) and giving it NSData. If you want to use that method to get NSData from an Image, you need to make self.image of UIImage type instead of NSData. Maybe init your variable image with UIImage(named: "imageName") if the image is bundled.

Display image from URL in swift, unwrapping error

I'm trying to display image to imageView from URL. I successfully done it using synchronous method in a simple project. But this application is used for online store, so I took product information and image URL from a JSON file. which I'm sure I was successfully stored all the data in a product array. But the problem I'm facing is this:
fatal error: unexpectedly found nil while unwrapping an Optional value
Here is the code.
// UnWrapping imageURL
let url:NSURL? = NSURL(string: actualCurrentProduct.imageURL)
if let actualURL = url {
let imageData = NSData(contentsOfURL: actualURL)
if let actualImageData = imageData {
self.productImageView.image = UIImage(data: actualImageData)
}
}
It highlighted in this particular code.
self.productImageView.image = UIImage(data: actualImageData)
Anybody have any idea why? Really appreciated it.
I managed to display the image successfully from URL with this code. I started the project from the scratch and for the display image part, here is my code.
let imageURL = NSURL(string: actualCurrentProduct.imageURL)
if let actualImageURL = imageURL {
let imageData = NSData(contentsOfURL: actualImageURL)
if let actualImageData = imageData {
let image = UIImage(data: actualImageData)
if let actualImage = image {
self.productImage.image = actualImage
}
}
}
Finally....

Resources