Decode base64 data for an image

This code no longer works with Swift 3.

imageData = NSData(base64EncodedString: mediaFile, options: NSDataBase64DecodingOptions.fromRaw(0)!) 

Here is this one.

 imageData = NSData(base64EncodedString: mediaFile, options: .allZeros) 
+6
source share
5 answers

Instead of using NSData use Swift 3 native Data directly.

 if let decodedData = Data(base64Encoded: mediaFile, options: .ignoreUnknownCharacters) { let image = UIImage(data: decodedData) } 
+12
source

Swift

Swift 3.0 does not recommend using NS anymore 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]; 
+4
source

I implemented this as a 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() } } 
+2
source

swift4:

Sometimes a string has a prefix, such as data:image/png;base64, , which will make base64Encoded return nil :

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

full code:

 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)!) } } catch let error { print("invalid regex: \(error.localizedDescription)") return [] } } } let result = text.matches(for: "data:image\\/([a-zA-Z]*);base64,([^\\\"]*)") for imageString in result { autoreleasepool { let image = imageString.base64ToImage() } } } 
+2
source

You can write like this:

 let data = NSData(base64Encoded: mediaFile, options: NSData.Base64DecodingOptions(rawValue: 0)) 

Hope this helps you.

+1
source

Source: https://habr.com/ru/post/1012881/


All Articles