如果图片的高度/宽度超过限制,使用CarrierWave调整图像大小

3

我已经搜索过并且尝试自己解决问题,但未能找到解决方案。当用户上传照片时,如果其超出了我的最小和最大尺寸,则希望将其调整大小。但是我想要两个条件。拍摄横向(东/西)的照片应保持在我设置的尺寸范围内,竖向(北/南)拍摄的照片也是如此。

例如,如果用户上传一张长边呈现的照片,其尺寸为3264x1840。则应将其调整为584x329以适应上传。如果上传文件小于584x329,则不会调整其大小。

另一个例子是,如果用户上传了一张竖着拍摄的照片,其尺寸为2448 x 3264。则应将其调整为247x329。

我试图使用MiniMagick实现这一点,因为我相信那是必需品。如果只能使用CarrierWave那就太好了,但我认为MiniMagick是用于调整图片大小的。

我收到的错误是“undefined method resize' for #<ImageUploader:0x007f8606feb9b8>'”,并指向控制器中的@photo = Photo.new(params[:photo])的def create。

顺便说一下,这些尺寸很高,因为这些通常是您上传照片时手机的默认尺寸。

image_uploader.rb:

class ImageUploader < CarrierWave::Uploader::Base

   include CarrierWave::MiniMagick

 storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end


  process :resize => [584, 329]

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

  # Create different versions of your uploaded files:
   version :thumb do
     process :resize_to_limit => [200, 200]
   end

end

照片控制器:

  def create
    @photo = Photo.new(params[:photo])
    @photo.user = current_user
    if @photo.save
      flash[:notice] = "Successfully created photos."
      redirect_to :back
    else
      render :action => 'new'
    end
  end

def resize(width, height, gravity = 'Center')
  manipulate! do |img|
    img.combine_options do |cmd|
      cmd.resize "#{width}"
      if img[:width] < img[:height]
        cmd.gravity gravity
        cmd.background "rgba(255,255,255,0.0)"
        cmd.extent "#{width}x#{height}"
      end
    end
    img = yield(img) if block_given?
    img
  end
end
1个回答

2

将图像上传器中的:resize更改为process :resize_to_fit => [584, 329]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接