我有一个我发送到服务器的NSInputStream,在上传过程中,我想显示上传的图像。方法位于单例中,它接收NSInputStream。有没有办法读取该流并将其转换为UIImage?
我已经尝试过这个,但没有运气。我的错误在哪里?
var buffer = [UInt8](count:1024, repeatedValue: 0)
thumbnailStream.open()
if (thumbnailStream.hasBytesAvailable){
let len : Int = inputStream.read(&buffer, maxLength: buffer.count)
var pictureData = NSData(bytes: buffer, length: len)
var imagess = UIImage(data: pictureData)!
self.headerProgress.imageView.image = imagess
print("Data of image = \(pictureData.length)")
}else{
print("No bytes")
}
谢谢!
答案 0 :(得分:3)
我找到了解决这个问题的方法,并且它处于正常运行状态。
var count = 0
let dataOfTheImage = NSMutableData()
var buffer = [UInt8](count:1024, repeatedValue: 0)
thumbnailStream.open()
//MARK: Loop through thumbnail stream
while (thumbnailStream.hasBytesAvailable){
count = count + 1
print("Counter: \(count)")
//MARK: Read from the stream and append bytes to NSMutableData variable
let len = thumbnailStream.read(&buffer, maxLength: buffer.count)
dataOfTheImage.appendBytes(buffer, length: len)
//MARK: Size of the image in MB
let size = Float(dataOfTheImage.length) / 1024.0 / 1024.0
print("Data length = \(size)")
}
//MARK: Check if there are no bytes left and show the image
if (thumbnailStream.hasBytesAvailable == false){
thumbnailStream.close()
// var pictureData = NSData(bytes: buffer, length: len)
let progressImage = UIImage(data: dataOfTheImage)!
dispatch_async(dispatch_get_main_queue(), {() -> Void in
self.headerProgress.imageView.image = progressImage
})
}