在我们的项目中,当我们捕获图像时,我们将图像存储在本地应用程序路径中,并且采用加密格式。并添加一些信息。最后,我们压缩了所有图像并将其发送到服务器,这是我们当前的流程。
我们想要做的是将图像转换为数据并编码为base64格式。但是如何压缩所有图像(我们需要捕获5个以上的图像)。
压缩所有base64格式的字符串并将其发送到服务器。怎么做?
您是否想将图像保存在内存中并压缩所有这些图像并发送到服务器,而不是将图像存储在应用程序文件夹中?
答案 0 :(得分:-1)
1-将每个图像转换为数据并编码为base64格式并压缩:
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
print(strBase64)
使用chilkat的压缩字符串:https://www.example-code.com/swift/compress_decompress_string.asp
func chilkatTest() {
// This example requires the Chilkat API to have been previously unlocked.
// See Compression UnlockComponent for sample code.
var success: Bool
let sb = CkoStringBuilder()
var i: Int
for i = 1; i <= 20; i++ {
sb.Append("This is the original uncompressed string.\r\n")
}
let compress = CkoCompression()
compress.Algorithm = "deflate"
// Indicate that the utf-8 byte representation of the string should be compressed.
compress.Charset = "utf-8"
var compressedBytes: NSData
compressedBytes = compress.CompressString(sb.GetAsString())
// If the compressed data is desired in string format, then get the base64 representation of the bytes.
compress.EncodingMode = "base64"
var compressedBase64: String? = compress.CompressStringENC(sb.GetAsString())
print("Compressed Bytes as Base64: \(compressedBase64!)")
// Now decompress...
var decompressedString: String? = compress.DecompressString(compressedBytes)
print("The original string after decompressing from binary compressed data:")
print("\(decompressedString!)")
// To decompress from Base64...
compress.EncodingMode = "base64"
decompressedString = compress.DecompressStringENC(compressedBase64)
print("The original string after decompressing from Base64:")
print("\(decompressedString!)")
}
2-以json格式保存:
[
{"1": "strBase64FromStep1"},
{"2": "strBase64FromStep1"},
.
.
.
]
3-将json字符串保存到文本文件:
let file = "file.txt" //this is the file. we will write to and read from it
let text = "some text" //just a text
if let dir = FileManager.default.urls(for: .documentDirectory, in:
.userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */}
//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */}
}
4-将文件网址保存到UserDefaults:
fileURL From step 3
NSUserDefaults.standardUserDefaults().setObject(fileURL, forKey: "path")
NSUserDefaults.standardUserDefaults().synchronize()
5-随时要将其发送到服务器时使用此文件。