Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jekyll: Get width/height of an image without using an external plugin

I want to automatically add height and width attributes to all my images. It is perfectly done via this nice plugin, but I host my site on GitHub Pages where external plugins are not supported.

Question: How to prefill height/width attributes of an image without using a plugin?

Why do I need this?

My site works well even without height and width but I want to specify them because it is important from SEO point of view (you can find some details on its importance here).

like image 305
Sasha Shpota Avatar asked Oct 29 '22 00:10

Sasha Shpota


1 Answers

Writing an internal filter to do this using the fastimage gem is fairly simple. You can define your filter in the _plugins directory of your project (this is outlined in the Jekyll documentation)

As a very rough example, you could do something like this:

require 'fastimage'

module ImageSizeFilter
  def image_size(source, dimension = nil)
    # Get the image dimensions, throw an error on failure
    # NOTE: You may want to sanitize the input string provided here
    # see: https://github.com/sdsykes/fastimage#security
    size = FastImage.size(source, raise_on_failure: true)

    # Return the requested dimension, or both dimensions if nothing was specified
    return size[0] if dimension == 'w'
    return size[1] if dimension == 'h'
    return size unless dimension

    # Fail if the requested dimension is invalid
    raise 'Invalid image size dimension requested: ' + dimension
  end
end

Liquid::Template.register_filter(ImageSizeFilter)

Which would be used like so:

<img src={{source}}
     width="{{source | image_size: 'w'}}"
     height="{{source | image_size: 'h'}}"/>

Of course this still won't work with GitHub pages directly because custom plugins are not supported. To use custom plugins in general, one solution is to build the site locally and include it in the repository.

like image 130
mark.monteiro Avatar answered Nov 15 '22 07:11

mark.monteiro