Alex Eguia's Codeblog

gem blurred_image_tag

1 Mar 2017

Sometimes it is mandatory to insert an image in a fixed width/height wrapper, either for aesthetic reasons, a fixed-dimension container, or other circumstances. The problem of creating elements with a fixed width and height is that the content needs to be processed to fit the measurements, possibly flattenning the images.

There are solutions both from the server side and from the client side to find out where the images “overflows”, and to be able to adapt the style in each case, but many of these solutions require a load time. A close-to-perfect solution can be one based on pure CSS as explained on the article Forcing image aspect ratio via CSS.

To keep the Rails’ DRY[1] motto, I have developed a Ruby on Rails gem defining a new method called blurred_image_tag that prints an image fitting it to its parent container’s width/height without being flattened. Its usage and params are the same as the native image_tag method.

Example of the blurred_image_tag gem usage with portrait and landscape images within a forced dimension div.

The main difference with the native method is that it creates a double <img> tag on the HTML: the first one to paint the blurred background, and the second one to print the image itself. This way, and using the CSS filter function, we can create fixed width/height image containers that neither flatten nor cut them by any side, with a blurred and semi-opaque background generated by the same image. Also, regarding the loading time, the same image is being referred twice, therefore the loading time will be the same as printing just one image since the cache of the web browser will reuse it.

To get the most out of this gem, or to collaborate with it, you can see the code and documentation in Github.

Rubygemsblurred_image_tag

Githubblurred_image_tag


[1] Don’t Repeat Yourself https://en.wikibooks.org/wiki/Ruby_on_Rails/Getting_Started/Don%C2%B4t_repeat_yourself