如何在不下载的情况下从网址获取图像的宽度和高度?

Łuk*_*rka 13 nsurl uiimageview uiimage ios sdwebimage

我正在使用SDWebImage在单元格内显示图像.但它完美地配合了UImageView的框架,我在下面的代码中做了:

NSString * s =[NSString stringWithFormat:@"url of image to show"];
        NSURL *url = [NSURL URLWithString:s];
        [cell.shopImageView sd_setImageWithURL:url];
Run Code Online (Sandbox Code Playgroud)

我的UIImageView大小为50x50.

例如,来自网址的图片尺寸为990x2100,我的图片在给定的框架中显示效果不佳.在这种情况下,当hight更大时,我想通过适当的高度比调整图像大小以匹配宽度50.

有没有办法从URL检查图像的大小而不下载它并以可怕的方式分配内存?

aru*_*007 12

您可以从URL标头中获取此数据,在Swift 3.0中使用以下代码

 if let imageSource = CGImageSourceCreateWithURL(url! as CFURL, nil) {
     if let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary? {
          let pixelWidth = imageProperties[kCGImagePropertyPixelWidth] as! Int
          let pixelHeight = imageProperties[kCGImagePropertyPixelHeight] as! Int
          print("the image width is: \(pixelWidth)")
          print("the image height is: \(pixelHeight)")
       }
   }
Run Code Online (Sandbox Code Playgroud)


che*_*tem 7

尝试搞乱不同的contentMode选项以获得您想要的外观.一个例子可能是,cell.shopImageView.contentMode = UIViewContentModeScaleAspectFit;这只会使图像很好地适应,但实际上不会调整图像视图的大小.

以下是您的contentMode选项:UIViewContentModes

另一种选择可能是这样的:

NSData *data = [[NSData alloc]initWithContentsOfURL:URL]; UIImage *image = [[UIImage alloc]initWithData:data]; CGFloat height = image.size.height; CGFloat width = image.size.width;

然后,您可以根据图像高度/宽度的比例设置imageView高度/宽度.

  • 是的我不想创建一个使这个任务的内存使用率低:) (2认同)