繁体   English   中英

回形针条件样式

[英]Paperclip conditional styles

upload.html.erb提交一个包含数据的表单-包括图像和裁剪信息(x和y坐标,宽度和高度)-到名为update_image的控制器方法。 然后,我想将此信息传递给模型( picture.rb )并保存该图像的裁剪版本。

我正在使用Rails 5和Paperclip来存储图像。 我遇到了以下两个似乎无法解决的问题:

  1. 如何访问模型中的作物信息数据? 我不想将作物信息保存在数据库中。
  2. 在存在裁切信息时如何裁切图像? (我想使用相同的模型从其他没有裁剪功能的表单中上传常规文件)

非常感谢您的帮助!

upload.html.erb

<form action="/update_image" enctype="multipart/form-data" accept-charset="UTF-8" method="post">
  <input type="file" name="image" />
  <input type="hidden" name="crop_x" value="0" />
  <input type="hidden" name="crop_y" value="5" />
  <input type="hidden" name="crop_width" value="200" />
  <input type="hidden" name="crop_height" value="100" />
</form>

upload_controller.rb

def update_image
  picture = Picture.new(image: params[:image])
end

picture.rb

class Picture < ActiveRecord::Base
  has_attached_file :image, styles: {
    cropped: "-crop #{@crop_w}x#{@crop_h}+#{@crop_x}+#{@crop_y}",
    thumb: "100x100>"
  }
end

您正在寻找动态样式。

class Picture < ActiveRecord::Base
  attr_accessor :crop_needed
  has_attached_file :image, styles: Proc.new { |clip| clip.instance.attachment_sizes }

 def attachment_sizes
    crop_needed ? {
      cropped: "-crop #{@crop_w}x#{@crop_h}+#{@crop_x}+#{@crop_y}",
      thumb: "100x100>"
    } : {thumb: "100x100>"}
 end
end

从需要裁剪的控制器中:

def update_image
  picture = Picture.new
  picture.crop_needed = true if params[:crop_x].present?
  picture.image = params[:image]
  picture.save
end

在不需要裁剪的其他控制器上,只需将crop_needed设置为false即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM