Skip to content

Instantly share code, notes, and snippets.

@hitsujiwool
Created September 16, 2012 07:37
Show Gist options
  • Save hitsujiwool/3731461 to your computer and use it in GitHub Desktop.
Save hitsujiwool/3731461 to your computer and use it in GitHub Desktop.
CSS Sprite Generator
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
#
# CSS Sprite Generator
# require imagemagick
# require Ruby >= 1.9
# Usage:
# ruby csssprite.rb file1 file2 file3 [options]
# Options:
# --offset put each image at every <offset> pixel
# --horizontal put images horizontally
#
require 'optparse'
def create_sprite(images, offset = nil, is_horizontal = false)
raise 'This script needs imagemagick' if !imagemagick_exists?
sizes = `identify -format "%w %h\t" #{images.join(" ")}`.chomp.split("\t").map {|item| item.split(' ').map(&:to_i)}
positions = calc_positions(sizes, offset, is_horizontal)
base = base_size(sizes, offset, is_horizontal)
cmds = []
cmds << "convert -size #{base[0]}x#{base[1]} xc:transparent png:-"
positions.each_with_index do |position, i|
cmds << "composite -geometry +#{position[0]}+#{position[1]} #{images[i]} - png:-"
end
puts `#{cmds.join(' | ')}`
end
def calc_positions(sizes, offset, is_horizontal)
tmp = []
if offset
sizes.each_with_index do |item, i|
tmp << (is_horizontal ? [offset * i, 0] : [0, offset * i])
end
else
sizes.inject(0) do |res, item|
if is_horizontal
tmp << [res, 0]
res + item[0]
else
tmp << [0, res]
res + item[1]
end
end
end
tmp
end
def base_size(sizes, offset, is_horizontal)
if offset
if is_horizontal
[(sizes.length - 1) * offset + sizes.last[0], sizes.transpose[1].max]
else
[sizes.transpose[0].max, (sizes.length - 1) * offset + sizes.last[1]]
end
else
if is_horizontal
[sizes.transpose[0].inject(:+), sizes.transpose[1].max]
else
[sizes.transpose[0].max, sizes.transpose[1].inject(:+)]
end
end
end
def imagemagick_exists?
!(`which convert`.empty? || `which composite`.empty? || `which identify`.empty?)
end
OptionParser.new do |opt|
offset = nil
is_horizontal = false
opt.on('--horizontal [HORIZONTIAL]') do |i|
ARGV.unshift(i)
is_horizontal = true
end
opt.on('--offset OFFSET', Integer) do |i|
offset = i
end
opt.permute!(ARGV)
create_sprite(ARGV, offset, is_horizontal)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment