【问题标题】:Swift: How to understand that downloaded image is empty?斯威夫特:如何理解下载的图像是空的?
【发布时间】:2019-10-03 10:36:27
【问题描述】:

我用翠鸟下载图像,但有时图像存在,但为空。

示例:Sample Image 如何检测此类图像?

我的下载方式:

func downloadFrom(link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit, rounded: Bool = false, loader: IndicatorType = .none) {
        self.kf.indicatorType = loader
        guard let url = URL(string: link) else {
            return
        }
        let img = self.image

        if(rounded) {
            let roundedProcessor = RoundCornerImageProcessor(cornerRadius: 100, targetSize: CGSize(width: 200, height: 200), roundingCorners: .all, backgroundColor: nil)
            self.kf.setImage(with: url, placeholder: img, options: [.processor(roundedProcessor)], completionHandler: {
                (image, error, cacheType, imageUrl) in

                if (error == nil) {
                    DispatchQueue.main.async() { () -> Void in
                        if (self.contentMode != UIView.ContentMode.scaleAspectFit) {
                            self.contentMode = mode
                        }
                    }
                }
            })
        } else {
            self.kf.setImage(with: url, placeholder: img, completionHandler: {
                (image, error, cacheType, imageUrl) in

                if (error == nil) {
                    DispatchQueue.main.async() { () -> Void in
                        if (self.contentMode != UIView.ContentMode.scaleAspectFit) {
                            self.contentMode = mode
                        }
                    }
                }
            })
        }
    }

【问题讨论】:

  • TRY : 在 completionHandler 中检查图片大小。
  • 您能提供更多信息吗?如何检查?
  • if (error == nil)上面做print(image),检查是否为nil,同时检查image.size
  • prntscr.com/np97m5 - 检查代码。 prntscr.com/np97u4 - 结果。不幸的是,每张图片都不是零并且有大小:(@dahiya_boy

标签: ios swift image-processing


【解决方案1】:

见以下代码,从服务器获取图像后检查图像大小。如果文件大小为 0,则图像为空。

self.kf.setImage(with: url, placeholder: img, options: [.processor(roundedProcessor)], completionHandler: {
                (image, error, cacheType, imageUrl) in

  if let imageData = UIImagePNGRepresentation(image) {
     let bytes = imageData.count
        if  bytes > 0 {
            //getting image successfully
        }else{
            //Image size is 0 (image is empty)
        }
  }else{
    //Not getting image
  }
})

【讨论】:

  • OP 刚刚评论说“不幸的是,每个图像都不是 nil 并且有大小”
  • 是的,完美,这就是我建议检查图像大小的原因。
  • 不,他们总是有一个size > 0。试试curl -o image.png https://socialboardsbproduction.blob.core.windows.net/123/7ac2d246-9a4a-4550-8500-4b59533c3ba0.png && ls -lh image.png。你会看到,即使图像是空的,大小也是 1.3K
  • 我至少可以检查“bytes > 5000”。从未见过带有用户头像的小图片)谢谢,检查...
  • @AtulParmar yeeees,谢谢,Atul,它正在工作!!!只是将“如果字节> 0”更改为“字节> 5000”。非常感谢!还要感谢 regina_fallangi! ))
猜你喜欢
  • 1970-01-01
  • 2017-07-22
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多