swift - 使用数据(不是 NSData),实际上你如何制作 jpeg 的 utf8 版本?

标签 swift utf-8 httprequest

完全按照这里的解释,https://stackoverflow.com/a/30624755/294884

[It is a mistake to think that] the JPEG representation of an image is a UTF-8-encoded string. It's not. It's arbitrary binary data. UTF-8 strings aren't arbitrary sequences of bytes; there are rules about what bytes can follow other bytes.

事实上,在 Data 时代,如何最好地从图像制作 utf8 数据?

日常用例采用 http 形式。

我做了这样的事情,

    formData.append( "Content-Disposition etc".(using: .utf8)! )
    formData.append( "Content type etc".(using: .utf8)! )

    // now let's add a #@@%$%$% image

    let trueBinary = UIImageJPEGRepresentation(i, 0.10)!
    print("the size seems to be \(trueBinary.count)")
    
    let mystere = trueBinary.base64EncodedString(
                  options: .lineLength76Characters)
    
    formData.append( mystere.data(using: .utf8)! )

但是

A,这看起来很乏味,而且可能无论如何都行不通。

B,“lineLength”概念对我来说毫无意义,所以我只是猜测一些东西,然后在其中输入一些东西。

请注意,令人难以置信的是,如果您有一个 Data x 并使用 append 将一些字符串作为 utf8 添加到 x ..... 然后您添加一个“真正的”二进制数据,例如 x 的 jpeg 表示……实际上它是“x” - 哎哟!(它不只是“不添加二进制”,它会把 x 擦掉。)

最佳答案

这一行有问题:

let mystere = trueBinary.count.base64EncodedString(
              options: .lineLength76Characters)

问题是trueBinary是一个Data,而trueBinary.count是一个Int,而Int 没有 base64EncodedString 方法。你想要这个:

let mystere = trueBinary.base64EncodedString(
              options: .lineLength76Characters)

至于““lineLength”概念”:如果您不想,则不必指定行长度选项。可以说我不应该在你在问题中引用的答案中指定一个,因为 HTTP requests are not strictly MIME messagesare not subject to the MIME line length limit .您可以这样做:

let mystere = trueBinary.base64EncodedString()

关于swift - 使用数据(不是 NSData),实际上你如何制作 jpeg 的 utf8 版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43808693/

相关文章:

ios - 如何在 Swift 的 AppDelegate 中初始化 NSTimer

php - PHPMyadmin "tî ă jî șî pî"中的罗马尼亚语单词不正确?

c# - 需要在单元测试中向请求添加自定义 header

php - 计算各种语言单词的 PHP 库/类?

ios - 即使在重置授权 header 后,NSURLConnection 也会返回缓存的响应

Swift POST 请求不起作用

ios - 从数组中选择随机结构

swift - 快速检查 NSError 代码

swift - 如何检查 Sprite 节点是否改变位置

java - 如何在scala中获取笑脸的Unicode