将base64数据解码为图像

时间:2016-12-05 04:50:52

标签: uiimage base64 swift3 nsdata xcode8

此代码不再使用Swift 3。

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

这就是这个。

imageData = NSData(base64EncodedString: mediaFile, options: .allZeros)

4 个答案:

答案 0 :(得分:4)

<强>夫特

Swift 3.0不建议再使用NS和NSData同样的情况

 if let decodedImageData = Data(base64Encoded: mediaFile, options: .ignoreUnknownCharacters) {
        let image = UIImage(data: decodedImageData)
    }

在Objective-C

NSURL *url = [NSURL URLWithString:base64String];    
NSData *decodedImageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:decodedImageData];

答案 1 :(得分:4)

Swift 4.1

对于这种情况,有时字符串前缀为data:image/png;base64会使base64Encoded返回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

    }
}

演示代码:

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


let results = text.matches(for: "data:image\\/([a-zA-Z]*);base64,([^\\\"]*)")
for imageString in results {
    autoreleasepool {
        let image = imageString.base64ToImage()
        }
    }
}

答案 2 :(得分:2)

我将其实现为UIImage扩展

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

答案 3 :(得分:1)

你可以这样写

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

希望它能帮到你