Skip to content

Instantly share code, notes, and snippets.

@ksouthworth
Last active November 2, 2021 19:59
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 ksouthworth/f4deb2a40c7e345f908e35699f1f000a to your computer and use it in GitHub Desktop.
Save ksouthworth/f4deb2a40c7e345f908e35699f1f000a to your computer and use it in GitHub Desktop.
Ruby VIPS text overlay example
#!/usr/bin/ruby
require 'vips'
# $ ruby vips-overlay.rb [INPUT_FILE] [OUTPUT_FILE] [TEXT]
# $ ruby vips-overlay.rb [INPUT_FILE] [OUTPUT_FILE] [TEXT] [HEX_COLOR]
# $ ruby vips-overlay.rb vips-input.png vips-output.png "Your overlay text here" "#1c7cd8"
def hex_color_to_rgb_array(hex_color)
hex_color.match(/^#(..)(..)(..)$/)&.captures&.map(&:hex)
end
requested_color = hex_color_to_rgb_array(ARGV[3]) unless ARGV[3].nil?
puts "requested_color = #{requested_color}"
WHITE_COLOR_RGB = [255, 255, 255]
text_color_rgb = requested_color || WHITE_COLOR_RGB # RGB color
puts "text_color_rgb = #{text_color_rgb}"
text_margin = 50
text_position = {
x: "center",
y: 674
}
im = Vips::Image.new_from_file(ARGV[0], access: :sequential)
puts "input width = #{im.width}"
# make the text mask
text_max_width = im.width - (text_margin * 2)
text = Vips::Image.text(ARGV[2], width: text_max_width, dpi: 200, align: :centre, font: "sans bold 34")
puts "text width = #{text.width}"
# we make a constant colour image and attach the text mask as the alpha
overlay = (text.new_from_image(text_color_rgb)).copy interpretation: :srgb
overlay = overlay.bandjoin(text)
# overlay the text on the source image
text_x = text_position[:x] == "center" ? (im.width - text.width) / 2 : text_position[:x].to_i
text_y = text_position[:y] == "center" ? (im.height - text.height) / 2 : text_position[:y].to_i - (text.height / 2)
im = im.composite(overlay, :over, x: text_x, y: text_y)
im.write_to_file(ARGV[1])
puts "output image = #{ARGV[1]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment