Skip to content

Instantly share code, notes, and snippets.

@PatMurrayDEV
Last active October 6, 2018 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatMurrayDEV/33a47acca3b5ac0912aec78f9419a95a to your computer and use it in GitHub Desktop.
Save PatMurrayDEV/33a47acca3b5ac0912aec78f9419a95a to your computer and use it in GitHub Desktop.
Dynamically Generated Open Graph Images in Jekyll
require 'rmagick'
require 'rickshaw'
module Jekyll
class OGFilter < Liquid::Tag
def initialize(tag_name, text, tokens)
super
@text = text
end
def render(context)
# This creates an image id hash from the page id in Jekyll
id = context["page"]["id"].to_sha1
# Check if the file already exists in the 'opengraph' foldler, return early if it does
if(File.exist?("#{Dir.pwd}/opengraph/#{id}.png"))
puts "File exists #{Dir.pwd}/opengraph/#{id}.png}"
else
# Create an image list from ImageMagic using the base image
img = Magick::ImageList.new("#{Dir.pwd}/assets/artboard.png")
# Create a caption of the title in a smaller area and center aligned.
text = Magick::Image.read("caption:#{context["page"]["title"]}") {
self.fill = '#D85F46'
self.font = "SF-Pro-Display-Medium"
self.pointsize = 90
self.size = "950x500"
self.gravity = Magick::NorthWestGravity
self.background_color = "none"
}.first
date = Magick::Image.read("caption:#{context["page"]["date"].strftime("%e %B %Y")}") {
self.fill = '#333333'
self.font = "SF-Pro-Display-Medium"
self.pointsize = 40
self.size = "950x100"
self.gravity = Magick::SouthWestGravity
self.background_color = "none"
}.first
# Composite the two images over each other (witht the smaller text image being centred)
a = img.composite(text, Magick::NorthWestGravity, 70, 70, Magick::OverCompositeOp)
a = a.composite(date, Magick::SouthWestGravity, 70, 70, Magick::OverCompositeOp)
# Write out the file
a.write("#{Dir.pwd}/opengraph/#{id}.png")
end
# Get the site variable
site = context.registers[:site]
# Add the file to the list of static_files needed to be copied to the _site
site.static_files << Jekyll::StaticFile.new(site, site.source, "/opengraph/", "#{id}.png")
"/opengraph/#{id}.png"
end
end
end
Liquid::Template.register_tag('og_filter', Jekyll::OGFilter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment