resimagecrop – a responsive image solution

←Back to listing

Last week I attended the excellent Fronteers conference in Amsterdam and while listening to a talk by Marcos Cáceres on responsive images, I had a thought on a potential polyfill solution. When I arrived home, I thought about it some more and today I managed to put it into practice.

Please bear in mind that this is a work in progress, a thought, a beginning, and above all a polyfill. I am sure that there are things I haven’t thought of and there are probably many issues with it and this is ok.

It’s a simple RESS based PHP script called resimagecrop.php that takes a number of arguments and returns an image based on the values of those arguments. The possible arguments are:

  • image – the relative link to the original local image file
  • x – the percentage x co-ordinate value within the original image where a crop should begin
  • y – the percentage y co-ordinate value within the original image where a crop should begin
  • w – the pixel width of the original image that is to be cropped
  • h – the pixel height of the original image that is to be cropped
  • sc – the decimal scaling factor of the resulting image

Combining these arguments allows you to define how the image should be returned. For example:

<img src="resimagecrop.php?image=img/saumur-castle-loire-valley-france.jpg&sc=0.5" alt="A view of Saumur Castle in the Loire Valley in France" />
									


will return the image img/saumur-castle-loire-valley-france.jpg at a scale of 0.5.

Similarily

<img src="resimagecrop.php?image=img/saumur-castle-loire-valley-france.jpg&x=15&y=20&w=550&h=450" alt="A view of Saumur Castle in the Loire Valley in France" />
									


will return the same image, cropped from 15% from the top and 20% from the left, to a width of 550×450 pixels.

And finally

<img src="resImageCrop.php?image=img/saumur-castle-loire-valley-france.jpg&x=15&y=20&w=550&h=450&sc=0.2" alt="A view of Saumur Castle in the Loire Valley in France" />
									


will return the same result as the previous example but will also scale the image by 0.2 so the dimensions of the actual image returned are 110×90.

I have set up a simple example to show you the script in action, and the code itself is on GitHub.

Of course this only works on the image’s initial load so to increase its responsitivity you can combine it with something like Scott Jehl’s picturefill script. This allows you to specify different images to be loaded via media queries.

A working example using picturefill is also available.

Thoughts and opinions welcome as always.