【问题标题】:How convert NSInputStream to UIImage如何将 NSInputStream 转换为 UIImage
【发布时间】:2017-03-23 18:25:55
【问题描述】:

我有一个要发送到服务器的 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")
    }

谢谢!

【问题讨论】:

  • 你用过调试器吗?当您运行您发布的代码时,实际会发生什么?
  • 变量 pictureData 具有缓冲区计数 1024 的长度。我更改了计数的值,pictureData 的长度更改为计数的值,并且运行时失败并且代码的pictureData 行被突出显示。另外,我确定我将图像数据发送到此方法,因为媒体已成功上传到服务器。 @rmaddy
  • 您需要从输入流中读取所有数据,而不仅仅是前 1024 个字节。
  • 有没有办法获取流的大小?因为我无法预测带有图像的流有多少字节。
  • 你必须循环直到没有更多的数据。

标签: ios swift uiimage nsinputstream bytestream


【解决方案1】:

我已经找到了解决这个问题的方法,并且它可以正常工作。

    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
        })
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 2015-06-13
    • 2011-03-10
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多