Can not convert Base64 String to UIImage on IOS Swift3 - image

I have a string file that contains base64string of image. I'm sure that base64String is correct, because i used the website for checking:
https://codebeautify.org/base64-to-image-converter
with file data:
https://www.dropbox.com/s/10zjyzgcyv7s08m/data_base.txt?dl=1
(download and copy the content to the above website to generate the image )
But, On IOS Device , i can't convert it to image . This is my code (Swift3) :
if let filepath = Bundle.main.path(forResource: "data_base", ofType: "txt") {
do {
let text3 = try String(contentsOfFile: filepath, encoding: String.Encoding.utf8)
let dataDecoded : Data = Data(base64Encoded: text3, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
self.imageView.image = decodedimage
} catch {
}
}else {
print("file is not exist")
}
Please help me to find out the solution.

Related

Is there a way of producing a playground app?

Xcode newbie.(me.dumb)
First time poster.
I have the following code and it tested flawlessly in Xcode Playground(h/t D.Budd Data Science).
I want to turn the code into a MacOS app and I cannot fathom the correct Project and Settings
to do this or do I need to import the Playground into a Project and modify it?
Also this app needs to run in the background (ie, no Window/UI) as this would destroy the current window scene(MagicMirror), sort of like an Automater app can do. It would have an app icon, of course.
Thanks so much for any help.
import Cocoa
extension String{
// get the file name from string
func fileName() -> String{
return URL(fileURLWithPath: self).deletingPathExtension().lastPathComponent
}
// get the file extension from a string
func fileExtension() -> String{
return URL(fileURLWithPath: self).pathExtension
}
}
func readFile(inputFile: String) -> String{
//split the file extension and file name
let fileExtension = inputFile.fileExtension()
let fileName = inputFile.fileName()
//get the file URL
let fileURL = try! FileManager.default.url(for: .desktopDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let inputFile = fileURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension)
//get the data
do{
let saveData = try String(contentsOf: inputFile)
return saveData
} catch {
return error.localizedDescription
}
}
func writeFile(outputFile: String, stringData: String){
let fileExtension = outputFile.fileExtension()
let fileName = outputFile.fileName()
//get the fileURL
let fileURL = try! FileManager.default.url(for: .desktopDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let outputFile = fileURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension)
//save the data
guard let data = stringData.data(using: .utf8) else {
print("No Can Do")
return
}
do {
try data.write(to: outputFile)
print("data written: /data")
} catch {
print(error .localizedDescription)
}
let myData = readFile(inputFile: "test.txt")
writeFile(outputFile: "output.txt", stringData: myData)
}

Swift 3.1 How to insert image as base64 into body of HTTPS request

I want to send an image to server using HTTPS POST request. I need to send image as base64 data. I have converted image data to base64 encoded string, but I cannot convert it to Data to put it into httpBody.
//encode image to base64
let chosenImage = imageView.image
let imageData:NSData = UIImagePNGRepresentation(chosenImage!)! as NSData
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
let dataBase64: Data = Data(strBase64)
let uploadUrlString = "https://api.imgur.com/3/upload"
let uploadUrl = NSURL(string: uploadUrlString)
let uploadRequest = NSMutableURLRequest(url: uploadUrl! as URL)
uploadRequest.addValue("Client-ID f7e5521d5dd4245", forHTTPHeaderField: "Authorization")
uploadRequest.httpMethod = "POST"
uploadRequest.httpBody = imageData
let uploadSession = URLSession.shared
let postRequest = uploadSession.dataTask(with: uploadRequest as URLRequest) { (data, response, error) -> Void in
if let antwort = response as? HTTPURLResponse {
let code = antwort.statusCode
print(code)
}
}
postRequest.resume()
Saw some solutions on StakOverflow, but didn't get how to do it properly.
Please advise.
I had the same problem ... here is my solution to insert BASE64 String into email-body:
//SWIFT 3.x
//convert to Data
let image = UIImage(data: yourUIImage! as Data)
//convert to base64 String
let imageData: NSData = UIImagePNGRepresentation(image!)! as NSData
let imageStr = imageData.base64EncodedString(options:.endLineWithCarriageReturn)
// insert this into your HTML code
let tmpHTMLimage = "<img class=\"no-show\" src=\"data:image/png;base64," + imageStr + "\" alt=\"Image\" height=\"80\" width=\"80\"/>"
solution: use .endLineWithCarriageReturn and not
.lineLength64Characters!!!
I realy hope this will help some of you guys!
Finally I have changed code a bit according to some advised from Leo Dabus. And I have ensured that it works fine without any conversion to base64:
let chosenImage = imageView.image
let imageData = UIImageJPEGRepresentation(chosenImage!, 1)
let uploadUrlString = "https://api.imgur.com/3/upload"
let uploadUrl = URL(string: uploadUrlString)
var postRequest = URLRequest.init(url: uploadUrl!)
postRequest.addValue("Client-ID XXXXXX", forHTTPHeaderField: "Authorization")
postRequest.httpMethod = "POST"
postRequest.httpBody = imageData
let uploadSession = URLSession.shared
let executePostRequest = uploadSession.dataTask(with: postRequest as URLRequest) { (data, response, error) -> Void in
if let response = response as? HTTPURLResponse
{
print(response.statusCode)
}
if let data = data
{
let json = String(data: data, encoding: String.Encoding.utf8)
print("Response data: \(String(describing: json))")
}
}
executePostRequest.resume()
So when uploading an image, I'm getting body of the result in json and it shows me the link to uploaded image:
"link\":\"http:\\/\\/i.imgur.com\\/ePOUIyN.jpg\"},\"success\":true,\"status\":200}")

Decode a base64 data to image

This code doesn't working with Swift 3 anymore.
imageData = NSData(base64EncodedString: mediaFile, options: NSDataBase64DecodingOptions.fromRaw(0)!)
So is this one.
imageData = NSData(base64EncodedString: mediaFile, options: .allZeros)
Instead of using NSData use directly Swift 3 native Data.
if let decodedData = Data(base64Encoded: mediaFile, options: .ignoreUnknownCharacters) {
let image = UIImage(data: decodedData)
}
Swift 4.1:
Sometimes string has prefix data:image/png;base64 will make base64Encoded return nil, for this situation:
extension String {
func base64ToImage() -> UIImage? {
if let url = URL(string: self),let data = try? Data(contentsOf: url),let image = UIImage(data: data) {
return image
}
return nil
}
}
Demo code:
let results = text.matches(for: "data:image\\/([a-zA-Z]*);base64,([^\\\"]*)")
for imageString in results {
autoreleasepool {
let image = imageString.base64ToImage()
}
}
extension String {
func matches(for regex: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: self, range: NSRange(self.startIndex..., in: self))
return results.map {
//self.substring(with: Range($0.range, in: self)!)
String(self[Range($0.range, in: self)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
}
PS: For more about data uri:
https://en.wikipedia.org/wiki/Data_URI_scheme
https://github.com/nodes-vapor/data-uri
Swift
Swift 3.0 does not recommend to use NS any more and the same case with NSData as well
if let decodedImageData = Data(base64Encoded: mediaFile, options: .ignoreUnknownCharacters) {
let image = UIImage(data: decodedImageData)
}
In Objective-C
NSURL *url = [NSURL URLWithString:base64String];
NSData *decodedImageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:decodedImageData];
I implemented this as UIImage extension
extension UIImage {
/*
#brief decode image base64
*/
static func decodeBase64(toImage strEncodeData: String!) -> UIImage {
if let decData = Data(base64Encoded: strEncodeData, options: .ignoreUnknownCharacters), strEncodeData.characters.count > 0 {
return UIImage(data: decData)!
}
return UIImage()
}
}
You can write like this way
let data = NSData(base64Encoded: mediaFile, options: NSData.Base64DecodingOptions(rawValue: 0))
Hope it will help you

Swift. Can`t save file to DocumentDirectory. Whats wrong?

Here`s my code:
let fileName = "someFileName"
func saveDataToFile(urlStr:String){
let url = NSURL(string: urlStr)
var data:NSData!
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let directory = paths[0]
let filePath = directory.stringByAppendingPathComponent(self.fileName)
print(filePath)//prints /Users/.../Library/Developer/CoreSimulator/Devices/1013B940-6FAB-406B-96FD-1774C670A91E/data/Containers/Data/Application/2F7139D6-C137-48BF-96F6-7579821B17B7/Documents/fileName
let fileManager = NSFileManager.defaultManager()
data = NSData(contentsOfURL: url!)
print(data) // prints a lot of data
if data != nil{
fileManager.createFileAtPath(filePath, contents: data, attributes: nil)
}
}
Now I want to read this data:
func readDataFromFile(){
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let directory = paths[0]
let filePath = directory.stringByAppendingPathComponent(self.fileName)
print(filePath) // prints the same path
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath){
data = fileManager.contentsAtPath(filePath)
}else{
print("*****BAD*****") // always prints this which means that file wasn`t created
}
}
What`s wrong with the first func? What is the right way to save file to DocumentDirectory?
OK, in this case the answer was following:
First need to create directory (aka folder) and only after that create file inside that directory.
Added to code this:
let fullDirPath = directory.stringByAppendingPathComponent(folderName)
let filePath = fullDirPath.stringByAppendingPathComponent(fileName)
do{
try fileManager.createDirectoryAtPath(fullDirPath, withIntermediateDirectories: false, attributes: nil)
}catch let error as NSError{
print(error.localizedDescription)
}
And as I said after this you create your file:
fileManager.createFileAtPath(filePath, contents: data, attributes: nil)
Thanks to Eric.D
Hope someone will find this useful.

How to save and load file image by swift

I have UIImage (got from Parse - convert variable PFFile).
How can I save and load image from this variable?
let a = object["image"] as! PFFile
a.getDataInBackgroundWithBlock({ (data:NSData?, error:NSError?) -> Void in
if (error == nil) {
// I have image, but the next I don't know what I do
let image = UIImage(data:data!)
}
})
Save image png
func saveImage(image:UIImage,name:String){
let selectedImage: UIImage = image
let data:NSData = UIImagePNGRepresentation(selectedImage)
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let success = fileManager.createFileAtPath(path, contents: data, attributes: nil)
print(success)
// Check image saved successfully
let getImagePath = (path as NSString).stringByAppendingPathComponent(name)
if fileManager.fileExistsAtPath(getImagePath) {
// image save success
let image = UIImage(contentsOfFile: getImagePath)!
}
else{
// image save error
}
}
Save other file
static func saveFile(fileData:NSData,name:String)->Bool{
let success = NSFileManager.defaultManager().createFileAtPath(path+"/"+name, contents: fileData, attributes: nil)
return success
}

Resources