我正在尝试通过base64 String中的Swift通过TCP套接字连接发送和接收图像。
发送部分:
let compressedImage = nsImage.compressUnderMegaBytes(megabytes: 0.4)
var data: Data = compressedImage!.tiffRepresentation!
let bitmap: NSBitmapImageRep = NSBitmapImageRep(data: data)!
data = bitmap.representation(using: .png, properties: [:])!
let base64: String = "data:image/png;base64,\(data.base64EncodedString(options:.endLineWithLineFeed))**end"
socket?.sendMessage(message: base64)
发送功能:
func sendMessage(message: String) {
let data = message.data(using: .ascii)!
_ = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }
}
接收代码
private func readAvailableBytes(stream: InputStream) {
// let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: maxReadLength)
print("reading incomming data \n\n\n")
var buffer = [UInt8](repeating: 0, count: maxReadLength)
while inputStream.hasBytesAvailable {
let numberOfBytesRead = inputStream.read(&buffer, maxLength: maxReadLength)
if numberOfBytesRead < 0 {
break
}
if let receivedMsg = String(bytes: buffer[..<numberOfBytesRead], encoding: .ascii) {
delegate?.scoktDidRecivceNewMessage(message: receivedMsg)
}
}
}
委托
func scoktDidRecivceNewMessage(message: String) {
// print("Recived Command @ cient : \(message)")
if message.contains("data:image/png;base64,") {
hasStartedReadingImage = true
base64ImageFrame = message
}
if hasStartedReadingImage {
if message.contains("**end")
{
hasStartedReadingImage = false
base64ImageFrame.append(message)
var base64 = base64ImageFrame.replacingOccurrences(of: "data:image/jpeg;base64,", with: "")
base64 = base64.replacingOccurrences(of: "**end", with: "")
let nsImage = base64.base64Convert()
DispatchQueue.main.async {
self.imgStremingView.image = nsImage
}
}else
{
base64ImageFrame.append(message)
}
}
}
我无法在客户端接收正确的base64。 如果我做错了,那么通过TCP发送图像的最佳方法是什么?