Created
October 15, 2009 09:23
-
-
Save andreas/210849 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment