`
ddl1st
  • 浏览: 95800 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

rails3 paperclip 添加水印

阅读更多
https://gist.github.com/784445

rails new example -d=mysql


cd example


Gemfile 添加
gem 'paperclip'


bundle install


新建文件/lib/paperclip_processors/watermark.rb
module Paperclip
  class Watermark < Thumbnail
    def initialize(file, options = {}, attachment = nil)
      super
      @watermark_path = options[:watermark_path]
      @position = options[:position].nil? ? "SouthEast" : options[:position]
    end

    def make
      src = @file
      dst = Tempfile.new([@basename].compact.join("."))
      dst.binmode

      return super unless @watermark_path

      params = "-gravity #{@position} #{transformation_command.join(" ")} #{@watermark_path} :source :dest"

      begin
        success = Paperclip.run("composite", params, :source => "#{File.expand_path(src.path)}[0]", :dest => File.expand_path(dst.path))
      rescue PaperclipCommandLineError
        raise PaperclipError, "There was an error processing the watermark for #{@basename}" if @whiny
      end

      dst
    end
  end
end


rails g scaffold image title:string


rails g paperclip image image


rake db:create && rake db:migrate


app/models/image.rb
require 'paperclip_processors/watermark'
class Image < ActiveRecord::Base
 has_attached_file :image,
                    :processors => [:watermark],
                    :styles => {
                      :medium => {
                        :geometry => "300x300>",
                        :watermark_path => "#{Rails.root}/public/images/rails.png"
                      },
                      :thumb => "100x100>",
                    }
end


app/views/images/_form.html.erb
<%= form_for(@image,:html => {:multipart => true}) do |f| %>
  <% if @image.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@image.errors.count, "error") %> prohibited this image from being saved:</h2>

      <ul>
      <% @image.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
    <div>
      <%= f.label :title %>
      <%= f.text_field :title %>
    </div>
    <div>
     <%= f.label :image %>
     <%= f.file_field :image %>
    </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>


app/views/show.html.erb
<p id="notice"><%= notice %></p>

<p>medium:</p>
<%= image_tag(@image.image.url(:medium)) %>
<%= link_to 'Edit', edit_image_path(@image) %> |
<%= link_to 'Back', images_path %>

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics