Decode a base64 data to image

前端 未结 5 1795
广开言路
广开言路 2020-12-28 19:57

This code doesn\'t working with Swift 3 anymore.

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


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-28 20:22

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

提交回复
热议问题