How to get the image width (and height) on bash/CLI?

I like to solve my own issues, with my own code (or at least partially my own code).

I've built a Laravel package to render commonmark files with frontmatter as static pages before. But with the Core Web Vitals becoming a ranking factor, the regular image-tags didn't meet the requirements anymore.

Another package had to be built 💪️ to add explicit width and height to my images. The idea for the "SEO images for phpleague/commonmark" package was born.

To make actual use of it, I had to resize numerous images that were already part of my blog. But I wanted only the images that were too wide on regular.

Not being keen on manual work, I've opted to use PHP for the job once more:

php -r "echo getimagesize('https://rankletter.com/assets/blog/articles/keyword-cannibalization/example-for-keyword-cannibalization-min.png')[0];"

To explain what is happening here:

This in combination with the find command allows selecting images based on their respective width.

Looking for the height? If you are after a certain height, you can simply tweak the [0] to [1].

Please note: There might be cases where this fails or returns 0, you should always check if your output is sensible.

🙏🙏🙏

Since you've made it this far, sharing this article on your favorite social media network would be highly appreciated 💖! For feedback, please ping me on Twitter.

Published