How to make images responsive – the easy way
If you're browsing the internet from a phone, then you probably don't want high-quality images, as they would use up the data on your phone plan. Consider that a 3-megabyte image is not good when your phone's data plan only gives you 2,000 megabytes for an entire month.
Here's a simple way to make the images on your site responsive.
Step 1: Make a small version of your site's images
First, I used two bash commands to make a smaller version of all the images. The first command makes a folder called 300px_wide:
mkdir 300px_wide
The second command fills this new folder with a shrunken copy of all the images. For images that are already small (less than 300 pixels wide), it just copies the image instead of resizing it.
mogrify -path 300px_wide -resize '300>' -quality 50% *
For this to work, it requires that all your images are in a single folder, with no subfolders. Granted, your website may be different.
Step 2: Add srcset and sizes attributes to your image tags
Now I needed to update the image tags. I basically have a bunch of text that contains lines like
<img src="https://www.mywebsite.com/img/myimage.jpg">
I needed to change these lines to
<img
srcset='https://www.mywebsite.com/img/myimage.jpg 301w,
https://www.mywebsite.com/img/300px_wide/myimage.jpg 300w'
sizes='(max-width: 600px) 300px,301px'
src='https://www.mywebsite.com/img/myimage.jpg'
>
What we need here is some regex. I could run the regex on the text themselves, changing the text permanently. However, I went for a non-destructive option.
When the page is loading, this PHP looks for image tags in the article text and adds srcset and sizes attributes to them:
$article_text = preg_replace("/\<img src\=[\'\"]https?\:\/\/www\.(.*?)\/img\/(.*?)[\'\"]/","
<img
srcset='https://www.$1/img/$2 301w,
https://www.$1/img/300px_wide/$2 300w'
sizes='(max-width: 600px) 300px,301px'
src='https://www.$1/img/$2'
",$article_text);
Leave a comment