我通过了 railscast 演练http://railscasts.com/episodes/182-cropping-images?autoplay=true。我可以使用回形针上传图像并选择我的裁剪区域。问题是当我点击提交时,图像没有被裁剪。我不认为图像正在被重新处理。我正在使用 rails cast 中的所有代码。我只是更改了变量名称以适合我的项目(@product 而不是 @user,图像而不是头像等...)
这是我的产品型号
class Product < ActiveRecord::Base
default_scope :order => 'title'
validates :title, :description, :presence => true
validates :price, :numericality => {:greater_than_or_equal_to => 0.01}
validates :title, :uniqueness => true
has_attached_file :image, :styles => { :small => "100x100#", :large => "500x500>" }, :processors => [:cropper]
attr_accessor :crop_x, :crop_y, :crop_w, :crop_h
after_update :reprocess_image, :if => :cropping?
def cropping?
!crop_x.blank? && !crop_y.blank? && !crop_w.blank? && !crop_h.blank?
end
def image_geometry(style = :original)
@geometry ||= {}
@geometry[style] ||= Paperclip::Geometry.from_file(image.path(style))
end
private
def reprocess_image
image.reprocess!
end
end
这是我的crop.html.erb 文件。在我提交带有附加图像的新产品表单后,控制器将重定向到此页面。
<% content_for(:head) do%>
<%= javascript_include_tag "jcrop/jquery.Jcrop.min", "jcrop/jquery.Jcrop" %>
<script type="text/javascript">
$(document).ready(function(){
$('#crop_box').Jcrop({
aspectRatio: 3/2,
onSelect: update_crop,
onChange: update_crop,
setSelect: [0, 0, 500, 500],
});
});
function update_crop(coords) {
var rx = 100/coords.w;
var ry = 100/coords.h;
$('#preview').css({
width: Math.round(rx * <%= @product.image_geometry(:large).width %>) + 'px',
height: Math.round(ry * <%= @product.image_geometry(:large).height %>) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
var ratio = <%= @product.image_geometry(:original).width %> / <%= @product.image_geometry(:large).width %>;
$("#crop_x").val(Math.round(coords.x * ratio));
$("#crop_y").val(Math.round(coords.y * ratio));
$("#crop_w").val(Math.round(coords.w * ratio));
$("#crop_h").val(Math.round(coords.h * ratio));
}
</script>
<% end %>
<%= image_tag @product.image.url(:large), :id => "crop_box" %>
<h4>Preview:</h4>
<div style="width:100px; height:100px; overflow:hidden">
<%= image_tag @product.image.url(:large), :id => "preview" %>
</div>
<% form_for @product do |f| %>
<% for attribute in [:crop_x, :crop_y, :crop_w, :crop_h] %>
<%= f.text_field attribute, :id => attribute %>
<% end %>
<p><%= f.submit "Crop" %></p>
<% end %>
下一段代码是 railscast 视频中的回形针处理器。它应该是根据裁剪选择处理实际裁剪的代码。
module Paperclip
class Cropper < Thumbnail
def transformation_command
if crop_command
crop_command + super.sub(/ -crop \S+/, '')
else
super
end
end
def crop_command
target = @attachment.instance
if target.cropping?
" -crop '#{target.crop_w.to_i}x#{target.crop_h.to_i}+#{target.crop_x.to_i}+#{target.crop_y.to_i}'"
end
end
end
end
不知道出了什么问题。我确信我错过了一些东西。如果比我更熟悉图像裁剪的人可以在这里帮助我,我将不胜感激。