how to get width and height of image from url without downloading?

Łukasz Szpyrka picture Łukasz Szpyrka · Jul 22, 2014 · Viewed 16.1k times · Source

I'm using SDWebImage for showing images inside cells. But it is perfect mached to frame of UImageView that I'm doing in code below:

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

My UIImageView is size 50x50.

For example image from url is size 990x2100 and my image is not displaying well in the frame given. In this case when hight is bigger, I want to resize my image by proper height ratio to match width 50.

Is there a way to check image's size from url without downloading it and allocating memory in awful way?

Answer

arunjos007 picture arunjos007 · Jul 18, 2017

You can fetch this data from URL header, in Swift 3.0 use below code

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