Carrierwave: Scale image if the size is larger than (conditionally create versions)

感情迁移 提交于 2019-12-05 02:13:34

问题


Is possible with carrierwave create a version (for example thumb) only if the image is larger than the size of the version??

Example:

version :thumb, :if => :is_thumbnable? do 
    process :resize_to_fit => [32,nil]
end

protected

def is_thumbnable?(file)
  image ||= MiniMagick::Image.open(file.path)
  if image.nil?
    if image['width'] >= 32 || image['height'] >= 32
      true
    else
      false
    end
  else
    false
  end
end

回答1:


I defined method in which if image exceed given width then manipulate it to your size the 32 pixels in this case. Put this code in your ImageUploader:

  version :thumb do 
    process :resize_to_width => [32, nil]
  end

  def resize_to_width(width, height)
    manipulate! do |img|
      if img[:width] >= width
        img.resize "#{width}x#{img[:height]}"
      end
      img = yield(img) if block_given?
      img
    end
  end



回答2:


I tried them and it didn't work for me. I get the server blocked when resizing to large images in development.

  • carrierwave (0.9.0)
  • rmagick (2.13.2)

So I get a look at the documentation: http://carrierwave.rubyforge.org/rdoc/classes/CarrierWave/RMagick.html

There is a wonderful function: resize_to_limit(width, height)

Resize the image to fit within the specified dimensions while retaining the original aspect ratio. Will only resize the image if it is larger than the specified dimensions. The resulting image may be shorter or narrower than specified in the smaller dimension but will not be larger than the specified values.

My code look like this:

version :version_name, from_version: :parent_version_name do
    process resize_to_limit: [width, nil]
end

It resize to fit the width only if it's larger, respecting the ratio w/h.




回答3:


Actually @Roza solution didn't work for me. I had to modify method like this:

process :resize_to_width => [650, nil]

def resize_to_width(width, height)
  manipulate! do |img|
    if img.columns >= width
      img.resize(width)
    end
    img = yield(img) if block_given?
    img
  end
end

I use rmagick (2.13.2) and rails 3.2.13, carrierwave (0.8.0)



来源:https://stackoverflow.com/questions/12391443/carrierwave-scale-image-if-the-size-is-larger-than-conditionally-create-versio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!