Skip to content

How to: Validate image geometry

Chris Sepic edited this page Aug 22, 2018 · 4 revisions

You can use a Rails custom validator to verify your image meets specific geometry dimensions requirements.

Grab a copy of the validator from https://gist.github.com/pioz/6b38e26c311d525fb48a and save it to your lib/ folder as file_geometry_validator.rb. Add the error translations to config/locales/en.yml or wherever is appropriate for your setup.

Then in your uploader you need to set an accessor attribute with the geometry of the image.

#app/uploaders/image_uploader.rb
class ImageUploader <  CarrierWave::Uploader::Base
 
  attr_accessor :geometry
 
  process :set_geometry
 
  version :thumb do
    process resize_and_pad: [64, 64, :transparent]
  end
 
  protected
 
  def set_geometry
    manipulate! do |image|
      @geometry = image.dimensions
      image
    end
  end
 
end

Then do this in your parent model:

# app/models/brand.rb 
require 'file_geometry_validator' 
class Brand < ActiveRecord::Base 
  mount_uploader :image, ImageUploader 
  validates :image, file_geometry: {is: [200, 200]}
end 

Accepts :maximum, :minimum, and :is options.

Clone this wiki locally