I am using 'SwiftSoup' SDK to parse HTML content from UIWebView. I want the image size and resolution for each and every image fetched from HTML content. How to get the image size and resolution as soon as an image is loaded and from HTML content received from SwiftSoup?
Asked
Active
Viewed 494 times
0
-
may help you: https://stackoverflow.com/questions/3936041/how-to-determine-the-content-size-of-a-uiwebview/3937599 – Mert Öksüz Mar 07 '18 at 14:18
-
For this you'll need to know when all images are loaded. – Cristik Mar 07 '18 at 14:34
1 Answers
0
Assuming you know when all images from the HTML are loaded, here's a javascript code that can be used to grab a list of sizes for all images:
let script = "JSON.stringify([].slice.call(document.getElementsByTagName('img')).map(function(img) { return {url: img.src, width: img.clientWidth, height: img.clientHeight} }))"
Executing this javascript via stringByEvaluatingJavaScript(from:) should give you a JSON that you can parse to obtain the desired info.
For example the output for this page is
[{"url":"https://i.stack.imgur.com/rQQMq.png?s=48&g=1","width":24,"height":24},{"url":"https://www.gravatar.com/avatar/46be6ae9d14855f5ab1aaf1d510ab8bc?s=32&d=identicon&r=PG&f=1","width":32,"height":32},{"url":"https://clc.stackoverflow.com/impression.gif?an=49ocs77evOWqh-6LVv8gJiaWI_07xL9f6GBcyDt7dl3NWtNsxo9-twOOBzKwMPRsYGBosGdkZGCRZuqawDHjMeecj4L_WRhSDiyObbJ82JRhP5vp7j6Og2e4ru0W9mRhmNs0gbnc8pVcsT0jc2Z-sTTTwxaOliucyy4LsrAwFLRcfRVt-e6KDEjTco4LjVyda4XkgZqaJcJzLa9Oj4RoMrJk4eJgYpBgYGDg4o1ij5VnYhAHsvk4o9gSmZgYRIBsfmYbtrvCTAxiIHH2ALapwv3t9i1z_NRrAA&md=291","width":0,"height":0}]
I'd recommend though to switch to WKWebView
since it's recommended also by Apple, and because stringByEvaluatingJavaScript(from:)
is blocking (WKWebView
provides an async version of this function, and one that also will do the parsing for you, so you can remove the JSON.stringify()
call from the script).

Cristik
- 30,989
- 25
- 91
- 127
-
When all images from the HTML are loaded,I am using a javascript code as mentioned above and I am receiving the same Output as mentioned above but for some images from few websites its giving me "width":0 and "height":0 even though image size is bigger ,any alternative solution for the same? When I download this url of image then it gives me proper image size. – Purvi Mehta Mar 09 '18 at 05:45
-
@PurviMehta could it be that the webview didn;'t download all the images? – Cristik Mar 09 '18 at 06:12
-
No, Webview download all the images but the above script doesn't provide proper image size. – Purvi Mehta Mar 12 '18 at 05:55