Invalid string in encoding image to base64 - Swift 4 - swift

my issue is when I try to encode an image to base-64, it generate a long string (up to 200,000 lines) and it doesn't work in the decoding, it generate a nil image! even I try to resize the image to a smaller size but still it doesn't work!
Here is my image encoding code
let image = imageView.image
let imageData:NSData = UIImagePNGRepresentation(image!)! as NSData
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
The decoding code:
let processImage = user.value(forKey: "processImage") as! String // image from json
if let dataDecoded:NSData = NSData(base64Encoded: processImage, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) {
let image: UIImage = UIImage(data:dataDecoded as Data,scale:1.0)!
print(image.size)
self.myImage.image = image }

You can try Following Steps:
Step :- 1 First Fetch the NSData from it
There are three Possibilities:
1. Using Image Name
let image : UIImage = UIImage(named:"imageNameHere")!
//Now use image to create into NSData format
let imageData:NSData = UIImagePNGRepresentation(image)!
2. Using NSURL:
//Use image's path to create NSData
let url:NSURL = NSURL(string : "urlHere")!
//Now use image to create into NSData format
let imageData:NSData = NSData.init(contentsOfURL: url)!
3. Image picked from image picker
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
let imageData:NSData = UIImagePNGRepresentation(image)!
Step:-2 Then Encode:
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
print(strBase64)
Step:-3 Then Decode:
let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImageView.image = decodedimage
Hope it helps.

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

convert image in swift4 to base64

let image: UIImage = UIImage(named:"imageView")!
let imageData: NSData = UIImagePNGRepresentation(image)! as NSData
base64String = imageData.base64EncodedString(options: .lineLength64Characters)
print(base64String as Any)
My problem is the variable (image) is null, but I'm sure I have selected the correct imageView
Your code will only work if the image exists in your asset catalog and the asset catalog is member of your target.
Maybe you just added the file to your project and not to the asset catalog? In this case try
guard let url = Bundle.main.url(forResource: "image", withExtension: "jpg") else {
return
}
guard let data = try? Data(contentsOf: url) else {
return
}
print(data.base64EncodedString())

Save UIImage array to disk

I have a UIImage array that I'm trying to save to disk (documents directory). I've converted it to Data so it can be saved but I can't figure out the correct/best way to save that [Data] to disk.
(arrayData as NSArray).write(to: filename, atomically: false) doesn't seem right or there seems like there is some better way.
Code so far:
// Get the new UIImage
let image4 = chartView.snapShot()
// Make UIImage into Data to save
let data = UIImagePNGRepresentation(image4!)
// Add Data image to Data Array
arrayData.append(data!)
// Get Disk/Folder
let filename = getDocumentsDirectory().appendingPathComponent("images")
// This is how I'd Write Data image to Disk
// try? data?.write(to: filename)
// TODO: Write array Data images to Disk
(arrayData as NSArray).write(to: filename, atomically: false)
To save your images to the document directory, you could start by creating a function to save your image as follows. The function handles creating the image name for you and returns it.
func saveImage(image: UIImage) -> String {
let imageData = NSData(data: UIImagePNGRepresentation(image)!)
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let docs = paths[0] as NSString
let uuid = NSUUID().uuidString + ".png"
let fullPath = docs.appendingPathComponent(uuid)
_ = imageData.write(toFile: fullPath, atomically: true)
return uuid
}
Now since you want to save an array of images, you can simply loop and call the saveImage function:
for image in images {
saveImage(image: image)
}
If you prefer to name those images yourself, you can amend the first function to the following:
func saveImage(image: UIImage, withName name: String) {
let imageData = NSData(data: UIImagePNGRepresentation(image)!)
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let docs = paths[0] as NSString
let name = name
let fullPath = docs.appendingPathComponent(name)
_ = imageData.write(toFile: fullPath, atomically: true)
}
When you save an image as a UIImagePNGRepresentation as you are trying to do, please note that is does not save orientation for you. This means that when you attempt to retrieve the image, it might be titled to the left. You will need to redraw your image to make sure it has the right orientation as this post will explain how to save png correctly. However, if you save your image with UIImageJPEGRepresentation you will not have to worry about all that and you can simply save your image without any extra effort.
EDITED TO GIVE ARRAY OF IMAGES
To retrieve the images you have saved, you can use the following function where you pass an array of the image names and you get an array back:
func getImage(imageNames: [String]) -> [UIImage] {
var savedImages: [UIImage] = [UIImage]()
for imageName in imageNames {
if let imagePath = getFilePath(fileName: imageName) {
savedImage.append(UIImage(contentsOfFile: imagePath))
}
}
return savedImages
}
Which relies on this function to work:
func getFilePath(fileName: String) -> String? {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
var filePath: String?
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if paths.count > 0 {
let dirPath = paths[0] as NSString
filePath = dirPath.appendingPathComponent(fileName)
}
else {
filePath = nil
}
return filePath
}
You can below code to stored image into local.
let fileManager = NSFileManager.defaultManager()
let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("ImageName.png")
let image = YOUR_IMAGE_TO_STORE.
let imageData = UIImageJPEGRepresentation(image!, 0.5)
fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)

Display base64 encoded image in imageview: SWIFT 3

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=="

CGImageSource to CGImage?

I got this following code that access a PHAsset. I need to pass a CGImage out of this:
let imageManager = PHImageManager.defaultManager()
imageManager.requestImageDataForAsset(self.asset!, options: nil, resultHandler:{
(data, responseString, imageOriet, info) -> Void in
let imageData: NSData = data!
if let imageSource = CGImageSourceCreateWithData(imageData, nil) {
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil)! as NSDictionary
//How do I create a CGImage now?
}
})
I need to extract a CGImage out of this. Having trouble getting there...
Once you have the image source you can create an image using CGImageSourceCreateImageAtIndex:
let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil)