Resize images with carrierwave if it exceeds height/width
我一直尝试环顾四周,但找不到解决方案。当用户上传照片时,如果它们超过我的最小和最大尺寸,我希望它们被调整大小。但是我想要两个条件。侧向拍摄的照片(东/西)应保持在我设置的尺寸范围内,高处拍摄的照片(北/南)也应保持相同。
例如,某用户上载了站立时间较长且尺寸为3264x1840的照片。上传文件的大小应调整为584x329。如果上载小于584x329,则不会调整大小。
另一个示例是,如果用户上传的照片是高大拍摄的,尺寸为2448 x3264。应调整上传大小以适合247x329。
我试图与此配合使用MiniMagick,因为我认为这是必需的。如果我只能使用CarrierWave,那是完美的选择,但是我认为应该使用MiniMagick来调整照片的大小。
我收到的错误是来自控制器中def create的'undefined method
BTW尺寸很高,因为通常这些尺寸是您上传照片时手机的默认尺寸。
image_uploader.rb:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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 |
照片控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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 |
将图像上传器中的