通过 NSData 将 UIImage 转换为 NSSString 时出错
Getting an error when converting UIImage to NSSString via NSData
我正在尝试将我的 UIImage
从 UIImageView
转换为字符串,因为数据存储为 Base64。我正在使用下面的方法来转换图像,但在尝试更新 convertedStr 时它会失败。
func convertImg() {
let imageData: NSData = UIImagePNGRepresentation(imageView.image!)! as NSData
convertedStr = NSString(data: imageData as Data, encoding: String.Encoding.utf8.rawValue)!
}
这个函数是关于版本 10 的,因为我尝试了不同的方法,但结果总是一样的。返回的错误是
'fatal error: unexpectedly found nil while unwrapping an Optional
value' and
'function signature specialization ) -> ()
to @callee_owned (@unowned Swift.UnsafeBufferPointer) ->
(@out ()), Argument Types : [@callee_owned (@unowned
Swift.UnsafeBufferPointer) -> ()]> of generic
specialization of
Swift.StaticString.withUTF8Buffer
((Swift.UnsafeBufferPointer) -> A) -> A'
会不会是我使用的方法需要一个 png 文件并且不适用于 UIImage
?
func convertImg() {
let imageData: NSData = UIImagePNGRepresentation(imageView.image!)! as NSData
convertstr = imageData.base64EncodedString(options: lineLength64Characters)
}
在Swift
编码为 swift 2.0 及更低版本
let image : UIImage = UIImage(named:"imageNameHere")!
//Now use image to create into NSData format
let imageData:NSData = UIImagePNGRepresentation(image)!
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
解码
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
print(decodedimage)
yourImageView.image = decodedimage
我正在尝试将我的 UIImage
从 UIImageView
转换为字符串,因为数据存储为 Base64。我正在使用下面的方法来转换图像,但在尝试更新 convertedStr 时它会失败。
func convertImg() {
let imageData: NSData = UIImagePNGRepresentation(imageView.image!)! as NSData
convertedStr = NSString(data: imageData as Data, encoding: String.Encoding.utf8.rawValue)!
}
这个函数是关于版本 10 的,因为我尝试了不同的方法,但结果总是一样的。返回的错误是
'fatal error: unexpectedly found nil while unwrapping an Optional value' and
'function signature specialization ) -> () to @callee_owned (@unowned Swift.UnsafeBufferPointer) -> (@out ()), Argument Types : [@callee_owned (@unowned Swift.UnsafeBufferPointer) -> ()]> of generic specialization of Swift.StaticString.withUTF8Buffer ((Swift.UnsafeBufferPointer) -> A) -> A'
会不会是我使用的方法需要一个 png 文件并且不适用于 UIImage
?
func convertImg() {
let imageData: NSData = UIImagePNGRepresentation(imageView.image!)! as NSData
convertstr = imageData.base64EncodedString(options: lineLength64Characters)
}
在Swift
编码为 swift 2.0 及更低版本
let image : UIImage = UIImage(named:"imageNameHere")!
//Now use image to create into NSData format
let imageData:NSData = UIImagePNGRepresentation(image)!
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
解码
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
print(decodedimage)
yourImageView.image = decodedimage