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

时间:2014-07-22 18:47:12

标签: ios uiimageview uiimage nsurl sdwebimage

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

NSString * s =[NSString stringWithFormat:@"url of image to show"];
        NSURL *url = [NSURL URLWithString:s];
        [cell.shopImageView sd_setImageWithURL:url];

我的UIImageView尺寸为50x50。

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

有没有办法从网址检查图像的大小而不下载它并以糟糕的方式分配内存?

4 个答案:

答案 0 :(得分:12)

您可以从网址标题中获取此数据,在 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)")
       }
   }

答案 1 :(得分:6)

尝试使用不同的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 :(得分:1)

  • 我不知道如何在不下载图片的情况下从网址获取图片大小。

  • 但我可以为您提供一些代码片段,以便在下载图像后按比例制作UIImageView帧。

    NSData *data = [[NSData alloc]initWithContentsOfURL:URL]; // -- avoid this.
    
  • 如果您使用上述方法下载图片,则会阻止您的用户界面。所以请避免它。

    [cell.shopImageView ....]; // -- avoid this method.
    
  • 当您使用 SDWebImage 时,我想它会有一些专门的方法来下载图像。因此,您可以使用该方法下载图像,而不是使用上面使用的UIImageView类别方法。

  • 下载图像后。尝试类似下面的内容。

  • 代码段

  • 假设下载图像并且对象是图像'和图像视图作为你的细胞imageview

    float imageRatio = theImage.size.width/theImage.size.height;
    float widthWithMaxHeight = imageView.frame.size.height * imageRatio;
    float finalWidth, finalHeight;
    if (widthWithMaxHeight > imageView.frame.size.width) {
        finalWidth = imageView.frame.size.width;
        finalHeight = imageView.frame.size.width/imageRatio;
    } else {
        finalHeight = imageView.frame.size.height;
        finalWidth = imageView.frame.size.height * imageRatio;
    }
    
    [imageView setFrame:CGRectMake(xOffset, yOffset, finalWidth, finalHeight)];
    [imageView setImage:theImage];
    

答案 3 :(得分:1)

 let ImageArray =  ((arrFeedData[indexPath.row] as AnyObject).value(forKey: "social_media_images") as? NSArray)!
 var ImageURL: String =  ((ImageArray[0] as AnyObject) as? String)!
 ImageURL = ImageURL.addingPercentEscapes(using: String.Encoding.ascii)!
   let imageUrl = URL(string: ImageURL)
   let imageData = try Data(contentsOf: imageUrl!)
    let image = UIImage(data: imageData)
print("image height: \(image?.size.height)"
  print("image Width: \(image?.size.width)")