【问题标题】:Rails carrierwave and minimagick allow landscape image onlyRailscarrierwave 和 minimagick 只允许横向图像
【发布时间】:2019-02-01 21:54:42
【问题描述】:

是否可以在图像上传时验证图像方向? 我希望该用户只能上传横向图片。

谢谢

【问题讨论】:

    标签: ruby-on-rails carrierwave minimagick


    【解决方案1】:
    mount_uploader :photo, PhotoUploader
    
    validate :check_landscape
    
    def check_landscape
      if photo.width<photo.height
         errors.add :photo, "is not a landscape." 
         puts "Error ! not a Landscape Image"
      else if photo.width>photo.height
         puts " Landscape Image"
      end
      end
    end
    

    如果您正在寻找 active_storage has_many_attached

    has_many_attached :images
    
    
    validate: active_storage_many_images
    
     def active_storage_many_images
        images.each do |image|
    
        image.blob.analyze unless image.blob.analyzed?
        width = image.blob.metadata[:width]
        height = image.blob.metadata[:height]
    
        if width<height
          errors.add :image, "Additional images are not landscape"
          puts "ACTIVE STORAGE IMAGE ERROR !!"
        end
      end
     end
    

    【讨论】:

    • 对您的代码进行更详细的解释将使提问者更容易理解您要传达的内容。我建议回过头来添加更多细节,说明为什么这是该问题的正确答案。它还将为可能遇到类似问题的其他用户提供更清晰的信息。
    • 没有特殊代码。只有简单的 ulploader,但我需要在加载肖像照片时引发错误
    【解决方案2】:

    因此,您需要的只是图像的 EXIF 元数据。我看到一个 gem 可以帮助我们从我们上传的图像中获取元数据,在这种情况下它似乎可以帮助你

    https://github.com/gzigzigzeo/carrierwave-meta

    基本上,我们可以得到 image_size 的大小,然后根据它创建一个验证依赖。

    【讨论】:

      猜你喜欢
      • 2011-05-30
      • 2013-07-02
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多