回形针调整大小的麻烦

时间:2019-01-19 05:39:47

标签: ruby-on-rails ruby paperclip

我的图像调整大小无法正常工作。我也安装了imagemagick。这是我当前图像的外观。 enter image description here

我希望它们都是相同大小的图像

<% products.each do |product| %>
    <div class="col-md-4">
        <div class="panel panel-default home">
            <div class="panel-heading preview">
                <%= image_tag product.cover_photo(:medium) %>
            </div>
            <div class="panel-body">
                <%= link_to product.name, product %><br/>
                $<%= product.price %> - <%= product.weight %><br/>
                <%= product.strain_type %><br/>
                <%= product.product_type %><br/>
                <span style="color: red;">THC: <%= product.percentage %>%</span>
            </div>
        </div>
    </div>
<% end %>

这是我的带回形针的photo.rb文件

class Photo < ApplicationRecord
  belongs_to :product

  # IMAGES FOR PRODUCTS
  has_attached_file :image, styles: { medium: "350x350>", thumb: "100x100>" }
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/


end

我的产品模型中有一个方法

class Product < ApplicationRecord
  enum instant: {Instant: 0, Request: 1}




    belongs_to :user
    has_many :photos, dependent: :destroy
  has_many :orders, dependent: :destroy
  has_many :guest_reviews , dependent: :destroy

    geocoded_by :address
    after_validation :geocode, if: :address_changed?

    def cover_photo(size)
    if self.photos.length > 0
      self.photos[0].image.url(size)
    else
      "blank.jpg"
    end
  end

  def thumbnail input
    return self.photos[input].variant(resize: '625x415!').processed
  end

  def average_rating
    guest_reviews.count == 0 ? 0 : guest_reviews.average(:star).round(2).to_i
  end
end

1 个答案:

答案 0 :(得分:0)

使用尾随(#),将对图片进行集中裁切,以确保达到要求的尺寸。

class Photo < ApplicationRecord
  belongs_to :product

  # IMAGES FOR PRODUCTS
  has_attached_file :image,
    styles: { medium: "350x350#", thumb: "100x100#" },
    convert_options: { :thumb => "-quality 60 -strip" }
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/

end

附加说明:

  • 转换时,您可以使用convert_options设置质量,以使其更小并且加载更快
  • 虽然可以选择适合图像的选项,但会产生一些结果 效果不好,特别是如果照片的尺寸相同时(例如有人上传) 尺寸为1000 x 500的照片,那么效果通常不好