我有一个从 Swift 保存到 mysql db 中的 Base64 字符串。当它返回时,它不显示图像。
它在数据库中的外观:
LzlqLzRBQVFTa1pKUmdBQkFRQUFTQUJJQUFELzRRQk1SWGhwWmdBQVRVMEFLZ0FBQUFnQUFnRVNBQU1BQUFBQg0KQUFFQUFJZHBBQVFBQUFBQkFBQUFKZ0FBQUFBQUFxQUNBQEZMUlUlJSUUFVVVVVQUZGRkZBQlJSUlFBVVVVVVUFGRkZGQUJSUlJRQVVVVVVBRkZZZKZZZVVVVVBRkZZKZ grkFCUlJSUUFVVQ0KVVVBRkZGaWdBcEtXaWdBcEtXaw0Kb0FLS0tLQUNpaWlnQW9vb29BS0tLS0FDaWlpZ0Fvb29vQVNpbG9vQVNpaWlnQW9vb29BS0tLS0FDaQ0KaWlnQW9vb29BS0tLS0FDaWlpZ0Fvb29vQUtLS0tB
这就是我尝试接收它的方式,但它不起作用:
let partUrl = "data:image/jpg;base64,";
let appndd = partUrl.stringByAppendingString(baseStringNew!)
let urlWeb = appndd
let requestURL: NSURL = NSURL(string: urlWeb)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
if error == nil {
NSLog("Success!")
dispatch_async(dispatch_get_main_queue(), {
imageNewView.layer.cornerRadius = 10.0
imageNewView.clipsToBounds = true
// Adding a border to the image profile
imageNewView.layer.borderWidth = 1.0
imageNewView.layer.borderColor = UIColor.grayColor().CGColor
imageNewView.image = UIImage(data:data!)
})
} else {
NSLog("Fail")
}
} //end of task
task.resume()
这将在 UIImageView 中显示一个空白图像。如何让此字符串显示为图像?
数据前面加上 data:image/png;base64
。
这里有一个问答,如何在UIImageView中显示base64图像?
您可能需要检查从MySQL数据库中存储和检索的base64字符串。尝试使用 BLOB 数据类型。
然后将base64字符串转换为NSData,然后UIImage非常简单明了。
let rawData = NSData.init(contentsOfURL: NSURL(string: "http://cdn.sstatic.net/stackoverflow/company/img/logos/so/so-logo.png")!)!
let base64String = rawData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
let imageData = NSData(base64EncodedString: base64String, options: .IgnoreUnknownCharacters)
let image = UIImage(data: imageData!)