【发布时间】:2021-12-30 01:07:00
【问题描述】:
我有一个如下的 json。我需要将图像转换为byte array 并将其发布为String。
我可以将图像转换为byte array,但如何将其转换为String?
将byte array 转换为String 时出现错误。
错误:
"not a valid UTF-8 sequence"
JSON:
"photo1": "[255,216,255,224,0,16,74,70,73, ..... ,]"
图像数据到字节数组:
func getArrayOfBytesFromImage(imageData:NSData) -> Array<UInt8> {
// the number of elements:
let count = imageData.length / MemoryLayout<Int8>.size
// create array of appropriate length:
var bytes = [UInt8](repeating: 0, count: count)
// copy bytes into array
imageData.getBytes(&bytes, length:count * MemoryLayout<Int8>.size)
var byteArray:Array = Array<UInt8>()
for i in 0 ..< count {
byteArray.append(bytes[i])
}
return byteArray
}
使用 getArrayOfBytesFromImage 函数:
if let string = String(bytes: getArrayOfBytesFromImage(imageData: imageData), encoding: .utf8) {
print(string)
} else {
print("not a valid UTF-8 sequence")
}
【问题讨论】:
-
您遇到的错误是什么?
-
“不是一个有效的 UTF-8 序列”这里 else 块总是有效的。
-
等一下,您显示的 JSON 是预期的结果吗?
-
json 有一个例子。它显示了我将发送的值作为示例。我查看了使用 app.quicktype.io 网站发送 json 的类型值。我需要将此数组作为字符串发送。