public
Created — forked from andreas/gist:210849

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
require 'RMagick'
 
class WatermarkMe
def initialize(app, args)
@app = app
@watermark_text, @mime_types = *args
@mime_types ||= %w[image/jpeg image/png image/gif]
end
def call(env)
status, headers, response = @app.call(env)
response = add_watermark(response) if use_watermark?(env, headers)
[status, headers, response]
end
def use_watermark?(env, headers)
@mime_types.include?(headers['Content-Type']) &&
!(env['HTTP_REFERER'] && env['HTTP_REFERER'].match(/^https?:\/\/#{env['HTTP_HOST']}/))
end
def add_watermark(response)
s = ''
response.each { |l| s << l }
image = Magick::Image.from_blob(s).first
mark = Magick::Image.new(image.columns, image.rows)
 
gc = Magick::Draw.new
gc.gravity = Magick::CenterGravity
gc.pointsize = 32
gc.font_family = "Helvetica"
gc.font_weight = Magick::BoldWeight
gc.stroke = 'none'
gc.annotate(mark, 0, 0, 0, 0, @watermark_text)
 
mark = mark.shade(true, 310, 30)
 
image.composite!(mark, Magick::CenterGravity, Magick::HardLightCompositeOp)
 
return image.to_blob
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.