'Get the image size in the web page by downloading only a small amount of data in the image header
A web page pointed to by a url contains many images(gif,png,jpg...), I just want to find the one with the largest size(eg: choose 1024x600 instead of 800x300) by Swift code.
Currently, I have to download all images locally and then get their sizes
I know that the size data of the image is actually only stored in its header, does this mean that I only need to download the small header data of the image to get its size?
If possible, how can I parse to the size of the image through its header data?
preferably Swift or C code, thanks! ;)
Or is there a better way to get the size of the image from web without downloading it locally? Please enlighten me, thank you!
Update:
I find some ruby code to do this:
PNG:
IO.read('image.png')[0x10..0x18].unpack('NN')
=> [713, 54]
GIF:
IO.read('image.gif')[6..10].unpack('SS')
=> [130, 50]
BMP:
d = IO.read('image.bmp')[14..28]
d[0] == 40 ? d[4..-1].unpack('LL') : d[4..8].unpack('SS')
Do these codes work? Thanks.
Solution 1:[1]
You can just create an URLRequest and set the httpMethod to "HEAD". Then you can call an URLSession dataTask with your request and check the expectedContentLength property of the response:
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let link = "https://i.stack.imgur.com/varL9.jpg"
let url = URL(string: link)!
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
URLSession.shared.dataTask(with: request) { data, response , _ in
guard let response = response, (response as? HTTPURLResponse)?.statusCode == 200 else { return }
DispatchQueue.main.async() {
print("data", data) // "data 0 bytes\n"
print("suggestedFilename:", response.suggestedFilename ?? "no suggestedFilename") // "suggestedFilename: varL9.jpg\n"
print("expectedContentLength:", response.expectedContentLength) // "expectedContentLength: 60807\n"
}
}.resume()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
