昨天我为此编写了一个工作代码,但是我删除了它,当写一个新的东西时真的很奇怪:
我用这种方式对它进行编码:
let pictureData = UIImagePNGRepresentation(picture!)
let pictureToString64 = pictureData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
(之前我有JPEGRepresentation,但它没有工作,所以我尝试使用JPEG)
我通过获取pic 64
来解码,我认为它具有正确的值。它以iVBORw0KGgoAAAANSUhEUgAAAUAA
(...)
let decodedData = NSData(base64EncodedString: pic64, options:NSDataBase64DecodingOptions(rawValue: 0))
let decodedImage = UIImage(data: decodedData!)
let pictureDataLocal = UIImageJPEGRepresentation(decodedImage!, 100)
defaults.setObject(pictureDataLocal, forKey: "profilePicture")
问题是decodeData总是为零。为什么会这样?
答案 0 :(得分:2)
我认为这与NSDataBase64DecodingOptions
有关。
使用NSDataBase64DecodingOptions.IgnoreUnknownCharacters
代替NSDataBase64DecodingOptions(rawValue: 0)
,我能够将Base64编码的字符串解码回NSData
,并从该数据创建UIImage
:
let picture = UIImage(named: "myImage")
let pictureData = UIImagePNGRepresentation(picture!)
let pictureToString64 = pictureData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
let decodedData = NSData(base64EncodedString: pictureToString64!, options:NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedImage = UIImage(data: decodedData!)
let pictureDataLocal = UIImageJPEGRepresentation(decodedImage!, 100)
NSDataBase64DecodingOptions
继承自OptionSetType
,这就是你获得rawValue初始化程序的原因。最好使用其中一种类型,而不是传入一个值。我在标题中看到NSDataBase64DecodingOptions
是结构中唯一的公共变量,所以我尝试了它。
@available(iOS 7.0, *)
public struct NSDataBase64DecodingOptions : OptionSetType {
public init(rawValue: UInt)
// Use the following option to modify the decoding algorithm so that it ignores unknown non-Base64 bytes, including line ending characters.
public static var IgnoreUnknownCharacters: NSDataBase64DecodingOptions { get }
}