In my swift App, I need to convert Image as String, then I need to send to Server , i.e POST. Then, if I need to GET, I dont want to decode that. Response having Image file name and path.
ONline Converter:
If I convert the sample image through online converter, HERE. I am getting following string. If I pass this string to API, I can get image successfully.
Output:
iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAYAAADnRuK4AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR.... .....CIBhIIgQRCIIEQSCAQAgmEQAIhkEAIJBAIgQRCIIEQSCAEEgiEQAIhkEAIJCgN/F+AAQAXoGXl+IGgwwAAAABJRU5ErkJggg==
Through My Coding
If I convert the sample image through Coding, I am getting following string. If I pass this string to API, Successfully adding. But, I unable to view that image manually in browser too.
More Over,, Two Output Strings are not same. I dont know why? Kindly guide me, how to solve this?
Code:
var image : UIImage = UIImage(named: "home_recharge.png")!
var imageData = UIImagePNGRepresentation(image)
let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
println("base64String \(base64String)")
Output:
iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAYAAADnRuK4AAAAAXNSR0IArs4c6QAAABxpRE9UAAAAAgAAAAAAAABIAAAAKAAAAEgAAABIAAAKygzM7MwAAAqWSURBVHgB7FwJ0JZDHC9yhJTkLuRMjuQ+opAr5zjGqAwZx...... .......FlIs5ASSDNQLA7EMtYMpBlICaQZKBYHYhlrBtIMpATSDBSLA7GMNQNpBlICaQaKxYFYxpqBNAMpgTQDxeJALGPNQJqBlECagWJxIJaxZiDNQP8B+6MkTad9NtcAAAAASUVORK5CYII=
You use png image representation but server saves the image with .jpg
extension so browser tries to read image as JPEG file and fails.
You should replace UIImagePNGRepresentation
with UIImageJPEGRepresentation
or save image with .png
extension.
The reason why browser can open online converter result image despite it has wrong extension is possibly that UIImagePNGRepresentation strips the image of its meta data and online converter not so browser can not figure the real type of image with wrong extension without meta data.