Display base64 encoded image in imageview: SWIFT 3 - swift

I have base64 image string which is downloaded from a webpage using POST request and I am trying to decode and display inside imageview but it's not working. I have tried couple of sources but no luck :(
let base64String = "data:image/jpg;base64,/9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="
Currently, trying this method:
if let decodedData = Data(base64Encoded: base64String, options: .ignoreUnknownCharacter) {
let image = UIImage(data: decodedData)
ImageView.image = image
} else {
print("error in decoding")
}
Tried NSData method also:
let dataDecode:NSData = NSData(base64Encoded: base64String!, options:.ignoreUnknownCharacters)!
let image= UIImage(data: dataDecode as Data)!
yourImageView.image = image
The else part always executes. I have tried this in xCode playground by putting encoded string in static variable and noticed nil in front of if condition line.
Not sure, what I am doing wrong?

Your base64String is actually a URL with a data scheme. There is built in support for these types of URLs.
You can do something like:
let dataString = "data:image/jpg;base64,/9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="
let dataURL = URL(string: dataString)
let data = Data(contentsOf: dataURL)
let image = UIImage(data: data)
I leave it as an exercise to properly handle optional values and error handling.

be careful, only part of the string represents the image
let base64String = "data:image/jpg;base64,9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="

Related

How to store an NSImage as Data in an app group on macOS

In iOS I can store UIImage to an app group as Data. I can convert the png image with pngData() to a Data object:
let imageData = scaledImage.pngData()!
I store that object in an app group, retrieve it and convert ik back to an UIImage:
let image = UIImage(data: imageData)
It's works great, but it doesn't work on macOS. MacOS doesn't have a UIImage, but a NSImage. How can I convert an NSImage tot Data and back?
Update: I use this code for macOS
let image = NSImage(named: "axl")!
let imageData = image.tiffRepresentation!
I store the imageData in a array.
In another part of the code I get the imageData from the array and convert it back:
let imageData = entry.images[0]
let image = NSImage(data: imageData)
Somehow the tiffRepresentation converting back with NSImage(data: ...) doesn't work.
Update: it does work!!
I use this code for macOS
let image = NSImage(named: "axl")!
let imageData = image.tiffRepresentation!
I store the imageData in a array.
In another part of the code I get the imageData from the array and convert it back:
let imageData = entry.images[0]
let image = NSImage(data: imageData)
It does work!!

Why is UIImage? nil here?

I'm trying to bridge React and Swift code by passing a string for an image path, which I've verified appears correctly on the Native side, and having a bit of an issue. The image path comes from React as NSString, and my goal is to pass that as a String to a Native function that will ultimately send data back to React.
Here's a snippet of some code that handles part of this
classifyImage(value as String)
and some of the body of the classifiyImage is as follows:
#objc func classifyImage(_ image: String) {
let imageData = Data(base64Encoded: image, options: .ignoreUnknownCharacters)!
let uiImage = UIImage(data: imageData)
guard let orientation = CGImagePropertyOrientation(
rawValue: UInt32((uiImage?.imageOrientation.rawValue)!)) else {
return
}
...code
}
The exact error is at the line with the rawVale, reading
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Here's more info if it may help...
Image data can come from the camera as such image NSMutableString "file:///var/mobile/Containers/Data/Application/54691469-2196-444E-9B45-C0D6F2CABEBC/Library/Caches/Camera/EEC3631C-3E96-44DA-B258-411363A2F10C.jpg" 0x00000002815a8420
or from the phone's gallery image String "ph://8F109DC0-CE95-4D0A-9D11-1B2E9CE6B8D3/L0/001"
Image from a file
First, we need to turn the string into a URL, then the URL into data like so:
let url = URL(string: image)
do {
let data = try Data(contentsOf: url)
} catch {
print(e)
}
Then we can use it to create the image.
do {
let data = try Data(contentsOf: url)
let image = UIImage(data: data)
guard let orientation = CGImagePropertyOrientation(
rawValue: UInt32(image.imageOrientation.rawValue)) else {
print("that didn't work")
return
}
} catch {
print(e)
}

Cannot convert URL to Data(contentsOf: URL) in swift5

I know there are many solutions around related to converting an Image string into data and to set the image in an ImageView. But unfortunately, nothing worked in my case. I have a parsed JSON field which returns an Image as a string. So I'm trying to convert that String as URL and then to get URL data to display the image. But when the error is throwing when I try to get the data from URL like
let testImage = Data(contentsOf: forecastURL! as URL)
Error: "Incorrect argument label in call (have 'contentsOf:', expected
'dictionary:')"
if let url21 = URL(string: brandingLogo) {
do {
let testImage = Data(contentsOf: url21)
self.BrandingBarImage.image = UIImage(data: testImage)
}
catch
{
print("error")
}
}
**Code for brandingLogo:**
guard let url = URL(string: urlJson) else {return}
let task = URLSession.shared.dataTask(with: url) { (data1, response, error) in
do {
let parsedData = try JSONSerialization.jsonObject(with:data1!) as? [String:Any]
let statusList = parsedData?["data"] as? [String:Any]
let anotherData = statusList?["data"] as? [String:Any]
if let players = anotherData?["players"] as? [[String:Any]] {
for logo in players {
self.brandingLogo = logo["logo_app_branding_bar"] as? String
print(self.brandingLogo)
}
brandingLogo is parsed from Json and its value is: https://media.socastsrm.com/wordpress/wp-content/blogs.dir/223/files/2018/01/blank-300x95.png
so, I'm assuming that when this 'brandingLogo' is considered as String, it takes only the actual string like :
https://media.socastsrm.com/wordpress/wp-content/blogs.dir/223/files/2018/01/blank-300x95.png
And so I'm trying to convert that image string to URL and then to get Data
Any help is appreciated. Thank you

How to use vapor for uploading/downloading image?

Now: i am uploading data and saving it to my public folder:
let info = req.data
guard let fileBytes = info["photo"]?.bytes
else {
var answerJson = JSON();
try answerJson.set("success", "false");
return answerJson
}
let dir = URL(fileURLWithPath: self.config.workDir).appendingPathComponent("Public/FleaMarketProductImages")
let dirWithImage = dir.appendingPathComponent("test3.jpg")
let fileManager = FileManager()
let data = Data(bytes: fileBytes)
fileManager.createFile(atPath: dirWithImage.path, contents: data, attributes: nil)
Then on device for downloaing this file i am doing next:
Alamofire.download(url).responseData { response in
if let data = response.result.value {
completionHandler(data)
}
}
I am getting some data, but when i do UIImage(data: data), i dont see my image. Where i did something wrong? Maybe there is another way to do it. And files in my public directory dont looks like image. They just files. Maybe do you know how to save it like an image????
The uploaded image will be one part of a multi-part request, so you need to use just the part that contains the image. .bytes will give you the whole request. I use:
guard let fileBytes = info.formData?["photo"]?.part.body
Or
guard let fileBytes = info?["photo"]?.part.body
if you aren't using a form.

How to load assign an image from url to cocos2d control using swift?

I am trying to figure out how to load an image via it's url (think facebook profile picture) in a cocos2d game. Can someone help me? I'm using swift but have no idea how to get this image displayed on the UI. Here is what I have so far...
if let currentUserName = PFUser.currentUser()!["profilepic"] as? String {
if let url = NSURL(string: currentUserName) {
if let data = NSData(contentsOfURL: url){
}
}
if let profilePic = PFUser.currentUser()!["profilepic"] as? String {
if let url = NSURL(string: profilePic) {
if let data = NSData(contentsOfURL: url){
imgView.image = UIImage(data: data!) //where imgView is your UIImageView
}
}
}