gpt4 book ai didi

ios - 编码/解码 base64 decodedData = nil

转载 作者:可可西里 更新时间:2023-11-01 01:37:47 24 4
gpt4 key购买 nike

昨天我为此写了一个工作代码,但我删除了它,当写一个新的代码时,有些东西真的很奇怪:

我用这种方式编码图片:

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")

问题是 decodedData 总是 nil。为什么会这样?

最佳答案

我认为这与 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 初始值设定项的原因。最好使用其中一种集合类型,而不是传入一个值。我在 header 中看到 NSDataBase64DecodingOptions 是结构中唯一的公共(public)变量,所以我试了一下。

@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 }
}

关于ios - 编码/解码 base64 decodedData = nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34228172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com