Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 826
Chris Mikkelsen Avatar asked Dec 05 '16 04:12

Chris Mikkelsen


People also ask

How do I decode a Base64 file?

To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.

Can I decrypt Base64?

Base64 is an encoding, the strings you've posted are encoded. You can DECODE the base64 values into bytes (so just a sequence of bits). And from there, you need to know what these bytes represent and what original encoding they were represented in, if you wish to convert them again to a legible format.


2 Answers

Instead of using NSData use directly Swift 3 native Data.

if let decodedData = Data(base64Encoded: mediaFile, options: .ignoreUnknownCharacters) {
    let image = UIImage(data: decodedData)
}
like image 68
Nirav D Avatar answered Sep 24 '22 07:09

Nirav D


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

like image 20
hstdt Avatar answered Sep 21 '22 07:09

hstdt