How do I set up responsive images in modx?

I want to be able to generate 3 copies of an image when it is saved as a TV. The copies would be scaled for mobile, tablet, and desktop. Then they would each be saved to different paths similar to /mobile /tablet /desktop.

The method that I have found for doing this is to assign a target width and height property to the image TV. Then create an event listener that will listen for an image tv to be changed. Then it will create the copies of the image, zoom crop them, using phpThumb, to their different target resolutions and save them to their respective paths and then I would need to change the tv value just to the files name.

Is this a good method for this?
I have looked for extras that do this and haven’t found any.

I wouldn’t normally look to save multiple versions of the TV image explicitly for this - instead, I’d let pThumb do the work for me.

Here’s an example of the markup to use a single TV setting (your-image-tv) to generate different-sized images for different breakpoints:

<picture>        
    <source media="(min-width:2400px)" srcset="[[+your-image-tv:pthumb=`w=3200&aoe=0&f=webp`]]">        
    <source media="(min-width:1200px)" srcset="[[+your-image-tv:pthumb=`w=2400&aoe=0&f=webp`]]">
    <source media="(min-width:1px)"    srcset="[[+your-image-tv:pthumb=`w=1200&aoe=0&f=webp`]]">
    <img src="[[+your-image-tv:pthumb=`w=2400&aoe=0&f=webp`]]"  alt="your alt text" class="styles-classes-here"/>
</picture> 

You can play with this to fit your own preferred breakpoints depending on your project.

The <img> tag works as a fallback option if none of the source tags match - but it’s also where you specify other attributes like alt and class that will apply to whatever source matches the viewport.

I’m sure there are many other ways to achieve this sort of result - and it’d be interesting to hear how other people go about it.

2 Likes

Wow I have never seen this html tag before. I was just going to change the base href of the page to the different paths based off of the browser dimensions. This is a much cleaner and simpler solution.

Thank you!

1 Like

Glad it’s helpful - let us know how you get on.

Using this method - as I understand it - pThumb will actually create all four images and caches them.

But the user’s browser will only load the image that matches their current viewport - so it’s pretty efficient.