lib/yamg/icon.rb in yamg-0.3.8 vs lib/yamg/icon.rb in yamg-0.5.0
- old
+ new
@@ -12,28 +12,31 @@
# Icon.new(src, size, rounded).image
# Image class
# Icon.new(src, size, rounded).image('.path.ext')
# Export image
#
- def initialize(src, size, rounded = false, radius = 9)
- fail if src.nil? || src.empty?
+ # ICO: 16/32/48
+ #
+ def initialize(src, size, bg = nil, rounded = false, radius = 9)
+ fail 'No source' if src.nil? || src.empty?
@src = src
@size = size
@rounded = rounded
@icons = YAMG.load_images(src)
YAMG.puts_and_exit("No sources in '#{src}'") if icons.empty?
@choosen = File.join(src, find_closest_gte_icon)
- @radius = radius
+ @radius = radius || 9
@dpi = 90
+ @bg = bg
end
alias_method :rounded?, :rounded
def find_closest_gte_icon
- return icons.max_by(&:to_i) if icons.map(&:to_i).max < size
+ proc = ->(x) { x.tr('^0-9', '').to_i }
+ return icons.max_by(&proc) if icons.map(&proc).max < size
icons.min_by do |f|
- # n = x.match(/\d+/).to_s.to_i
- n = f.to_i
+ n = proc.call(f)
size > n ? Float::INFINITY : n
end
end
def radius
@@ -82,31 +85,64 @@
i.compose 'Over'
end
masked
end
+ def apply_background
+ clone = ::MiniMagick::Image.open img.path
+ clone.combine_options do |o|
+ o.draw 'color 0,0 reset'
+ o.fill @bg
+ end
+ clone.composite(img) { |i| i.compose 'Over' }
+ end
+
+ # Just copy the svg, never resize
+ def svg!
+ fail unless @icons.find { |i| File.extname(i) == 'svg' }
+ end
+
+ # ICO!
+ def ico!(out)
+ temp = ->(s) { "/tmp/#{s}-#{Thread.current.object_id}.png" }
+ MiniMagick::Tool::Convert.new do |o|
+ o << Icon.new(@src, 16).image(temp.call(16))
+ o << Icon.new(@src, 32).image(temp.call(32))
+ o << Icon.new(@src, 48).image(temp.call(48))
+ o.colors 256
+ o << out
+ end
+ end
+
def image(out = nil)
+ return svg! if out =~ /svg$/
+ return ico!(out) if out =~ /ico$/
temp = out || "/tmp/#{@choosen.object_id}.png"
if File.extname(@choosen) =~ /svg/
pixels = dpi ? "-d #{dpi} -p #{dpi}" : nil
args = "#{pixels} -w #{size} -h #{size} -f png"
YAMG.run_rsvg(@choosen, temp, args)
@img = MiniMagick::Image.open(temp)
+ @img.format File.extname(out) if out
+
else
@img = MiniMagick::Image.open(@choosen)
+ @img.format File.extname(out) if out
@img.resize size # "NxN"
end
+ @img = apply_background if @bg
@img = round if rounded?
- write_out(out)
+ out ? write_out(out) : img
end
#
# Writes image to disk
#
def write_out(path = nil)
return img unless path
FileUtils.mkdir_p File.dirname(path)
img.write(path)
+ path
rescue Errno::ENOENT
puts_and_exit("Path not found '#{path}'")
end
end
end