Skip to content

Instantly share code, notes, and snippets.

@pavanpodila
Created May 25, 2012 11:32
Show Gist options
  • Save pavanpodila/2787473 to your computer and use it in GitHub Desktop.
Save pavanpodila/2787473 to your computer and use it in GitHub Desktop.
Generate Favicons using RMagick. Includes a Middleman-3.0 extension
###
# Simple Script to generate favicons from a base PNG image
# Relies on RMagick to do the job
# Also includes a Middleman-3.0 extension
###
require 'fileutils'
class MagickFavicon
include Magick
attr_accessor :base_image, :source_dir, :target_dir
Icons = {
'favicon.ico' => '16x16',
'apple-touch-icon-144x144-precomposed.png' => '144x144',
'apple-touch-icon-114x114-precomposed.png' => '114x114',
'apple-touch-icon-72x72-precomposed.png' => '72x72',
'apple-touch-icon-57x57-precomposed.png' => '57x57',
'apple-touch-icon-precomposed.png' => '57x57',
'apple-touch-icon.png' => '57x57',
}
def initialize
self.base_image = 'favicon_base.png'
self.source_dir = 'source'
self.target_dir = 'tmp'
end
def make
# Load the base image
base_file = File.join(source_dir, base_image)
base_icon = ImageList.new base_file
# Generate!
Icons.each do |filename, size|
w, h = size.split 'x'
favicon = base_icon.scale(w.to_i, h.to_i)
favicon.write File.join(target_dir, filename)
favicon.destroy!
yield filename if block_given?
end
end
end
### Middleman Extension ###
module FaviconMaker
class << self
def registered(app)
app.after_build do |builder|
fm = MagickFavicon.new
fm.source_dir = source
fm.target_dir = build_dir
fm.make { |f| builder.say_status :generated, f }
FileUtils.rm_f File.join(build_dir, fm.base_image)
end
end
alias :included :registered
end
end
::Middleman::Extensions.register(:favicon_maker, FaviconMaker)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment