Convert Raw JSON response to image - ios

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)!
}

Related

Swift iOS how to convert bytes to Image

I'm trying to retrieve and visualize an image from postgres to iOS, and I tried turning into Data and then UIImage but with no luck, when i create the UIImage it returns nil.
As you can see from the image below, I get that string from the db, with double backslash and x, that should be normal, I tried both to keep the escaping symbols and to trim them, I also tried to initialize the Data with both initializer with byte: and base64Encoded, with and without options but the image is always nil.
screenshot from xcode
func dataToImage(data:String)->Image{
var imageData = Data(bytes: "68747470733a2f2f73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f696c6172696f73616c6174696e6f2f31423236303332462d363935422d344342432d393733412d3342413936343841334535372d373136312d303030303145323833464643303541442e6a706567", count: data.count)
var base64data = Data(base64Encoded: "68747470733a2f2f73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f696c6172696f73616c6174696e6f2f31423236303332462d363935422d344342432d393733412d3342413936343841334535372d373136312d303030303145323833464643303541442e6a706567", options: .ignoreUnknownCharacters)
return Image(uiImage: UIImage(data: imageData)!)
}
the string I get from the db:
data String "\\x68747470733a2f2f73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f696c6172696f73616c6174696e6f2f31423236303332462d363935422d344342432d393733412d3342413936343841334535372d373136312d303030303145323833464643303541442e6a706567"
Any help appreciated, thanks!
You are not saving image data correctly =/
To get UIImage Data properly you should:
let data = yourImage.jpegData(compressionQuality: 1)
It will return an Data
So, save it like a String and its ready!
To set image from Data its like these:
let data = Data(base64Encoded: myString)
let newImage = UIImage(data: data)
To debug more easily use this string to convert to Data and Image. This string provides us a Data and an Image properly
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABAAEADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+iiopp1gALg4PcUJXAloqut7A/Rqk+0Rf38fUYp2YrklFRfaIi2A2foM0vnR5wXAPoeKLMdySikDK3RgfoaWkAVma0+y1B9606x/EJIskx13VUdxPYp2zl1GVyParjvkx43KWUAnjPU+tZdr9zkVad9ph7jaOD9TWjJMnTNS+26C15qFqLuWCeZNkEIZmKsF+Vc9cGtJdetreFUOm6pFGP8ApxchRn2z61z+kmKOwmD25lA1S8C44x84rpYZBPHH5R8lyf4o2fPt1GKTVwFk1jTBLLE9ysTxOY2M0bRru54DMAG6djWxZ824+p/nWJHeyeV5cqyZxyy4x+RY1s6ec2i5OTk8n60pbDW5arE8SNi1jA/vf4Vt15/8TfFcPhlNOWW0kuftRfAjmEZXbg55Bz1pU4uUrLcJSUVeWxp2eMYLLj2rQKwtGjPjgAZ3ds14sPi3aRNkaHcH63i//E1KPjVAoH/EknGP+nxP/iK39hU7fkZqtTfU9A8P+W+m3LhA6nUrtlB/3x61src7GVvs06KByFjU5/EGvMvD3jS4/sTTYbTSDc3F891c4a8SMIPO28krz0qw3izWJHQroSfOQqn+04iOTjqU4qOR/wBNF8y/pM9GW4jIKrbThevEWB/OtrSz/omB2YivH4/GmqRoZ/7GhKDg/wDE1hHP/fI/WvRfAWvjxFoEt59m+zMly8LxecsuCoH8S8d6mUXa/wCqGpK9jdl02GYcy3S/7lzIv8mrJvvBOh6p5f8AaVu995efL+1yGUpnGcFs46CuhorNSa2HZHI/8Kx8H/8AQDtP+/K/4Up+GXg8qQdDtMEY4iUfyFdbRT55dwsjlE+G3hJLaG2/saCSGAMIll+fYGYsQC2SOSTTh8N/Bw/5l6wP1hFdTRRzS7hZHNL8PfCC/wDMu6cfrAprY03SNP0aBoNNs4rWFm3GOJdq59cdKu0UnJvdhZH/2Q=="
I hope it helped you!
Cheers
try this
class ImageConverter {
func base64ToImage(_ base64String: String) -> UIImage? {
guard let imageData = Data(base64Encoded: base64String) else { return nil }
return UIImage(data: imageData)
}
func imageToBase64(_ image: UIImage) -> String? {
return image.jpegData(compressionQuality: 1)?.base64EncodedString()
}
}

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 UIImage to base64 string in swift

I'm trying to convert a UIImage to a base64 string with the goal of uploading it to a back-end server.
However, the conversion code I found in this article (which should be Apple's own implementation) generates an invalid string:
Convert between UIImage and Base64 string
After upload, I get this image:
[Failty image that is decoded from iOS converted base64 1
Instead of this:
[Correct image decoded from an online base64 conversion tool2
I tested the upload results using Postman and the back-end handles a valid base64 image correctly, so I narrowed the bug down to the base64 conversion itself. Here's my code:
public extension UIImage
{
func base64Encode() -> String?
{
guard let imageData = UIImagePNGRepresentation(self) else
{
return nil
}
let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
let fullBase64String = "data:image/png;base64,\(base64String))"
return fullBase64String
}
}
Any idea how I could fix my base64 output on my iOS device before I upload it to the server?
Do it something like this:
For Encoding:
data.base64EncodedStringWithOptions([])
For decoding:
let url = URL(string: String(format:"data:application/octet-stream;base64,%#",base64String))
do {
let data = try Data(contentsOf: url!)
}catch {
}
for Swift 4,
Do something like this,
For Encoding -
let imgObj = UIImage(named: "photo")
let imageData = UIImagePNGRepresentation(imgObj!)! as NSData
let base64 = imageData.base64EncodedData(options: .lineLength64Characters)
datatype of base64 variable is Data.

Convert HEX String to UIImage

I have some request that returns a JSON string as the response.
I use the Alamofire framework, and in the function where I parse the JSON response:
if let img = jsonData["my_data"]["img"].string{
printl(img)
}
After that, I get the description
img = "\xffd8ffe000104a46494600010100000100010000ffdb0043000302020302020303030304030304050805050404050a070706080c0a0c0c0b0a0b0b0d0e12100d0e110e0b0b1016101113141515150c0f171816141812141514ffdb00430103040405040509050509140d0b0d1414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414ffc000110801e0035503012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a43444546474"
I need to convert this string into a UIImage. I tried doing it using the following code:
if let img = jsonData["status_order"]["img"].string {
let myData = img.dataUsingEncoding(NSUTF8StringEncoding)
// println(myData)
let base64String = myData!.base64EncodedStringWithOptions(.allZeros)
// println(base64String)
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))
var decodedimage = UIImage(data: decodedData!)
println(decodedimage)
my_pic.image = decodeimage // I get nil
}
But after that I get some errors:
2015-09-18 18:57:14.363 taxi-admin[1520:3e03] ERROR: unable to get the
receiver data from the DB!
2015-09-18 18:57:16.822 taxi-admin[1520:4e03] ERROR:
ForceShrinkPersistentStore_NoLock -delete- We do not have a BLOB or
TEXT column type. Instead, we have 5.

Convert String from JSON to UIImage

I'm receiving some JSON data from a webservice, which includes an image represented as a Sting.
How can I convert this string into an image?
The JSON data is in an NSDictionary, and the Image data is the Object form the "Content"-key:
if let newBannerContentString = newBanner.objectForKey("Content") as? String {
let someImage = UIImage(contentsOfFile: newBannerContentString)
}
This returns nil to someImage.
If string is base64 encoded you could create NSData from that string and image from that data.
if let newBannerContentString = newBanner.objectForKey("Content") as? String {
let data = NSData(base64EncodedString: newBannerContentString, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters);
let someImage = UIImage(data: data!);
}

Resources