Fetch size of resource without downloading

I need to determine a size of image before downloading an image from web. I don’t want to download those images that are too small. I need a filter. Primitive way to download an image from web

UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"IMAGE_URL"]]];

It downloads all the bytes. I can analyze the size. I don’t want this. Its wasting resources by downloading full bytes. I want to get the size information beforehand.

There is a way to get information. I can request/fetch header information of the content that is been served by the server. Check the information http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
HEAD request just returns header information of the resource. Information contains type of the resource file, size, server type etc. This never downloads the full resource and hence saves the resources. For my purpose I needed Content-Type and Content-Length. These properties are easily available to you in NSDictionary key-value representation. We can fetch the just header information

-(void) headRequest
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
                                    [NSURL URLWithString:@"IMAGE_URL"]];
    [request setHTTPMethod:@"HEAD"];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data,
                                               NSError *connectionError) {
                               NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
                               if ([httpResponse respondsToSelector:@selector(allHeaderFields)]) {
                                   NSDictionary *dictionary = [httpResponse allHeaderFields];
                                   NSLog(@"CONTENT-LENGTH %@", [dictionary objectForKey:@"Content-Length"]);

This is clean but still not reliable. Some server never returned “Content-Length”. This is disappointing. I was counting on this.

Earlier when I mentioned size, I assumed that bigger the bytes size than higher the image resolution. This wasn’t that straightforward as I assumed. Some resources are really optimised. It means their size was smaller and had a good size dimension. For that same size general images were too small. Conclusion was either the image was optimised or information was wrong. What minimum threshold value should I be using for a size?

Be the first to leave a comment. Don’t be shy.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>