Last active
December 15, 2015 19:59
-
-
Save tehprofessor/5315237 to your computer and use it in GitHub Desktop.
Image dimensions validation with carrierwave-vips
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'vips' | |
class Photo < ActiveRecord::Base | |
# Include the VIPS moduel in model so we have access to the `Image` class | |
include VIPS | |
# Basic attributes | |
attr_accessible :image, :image_cache, :crop_x, :crop_y, :crop_w, :crop_h | |
# mount Carrierwave | |
mount_uploader :image, PhotoUploader | |
# Call the minimum_dimensions method on validation | |
validate :minimum_dimensions | |
# Crop the photo if we need to | |
after_update :crop_image | |
# Minimum dimensions validation method | |
def minimum_dimensions | |
# Check to make sure we've got a file and nothing sketchy is going on | |
if self.image.file | |
# Read the image's path | |
file_path = self.image.file.path | |
# Use VIPS to read the image | |
image = Image.new(file_path) | |
# Add an error message specifying the minimum dimensions, | |
# if the image.x_size (width) or image.y_size is less than 400 pixels | |
# simply change the value if you need different minimums | |
errors.add(:image, "must be at least 400 x 400 pixels") if image.x_size < 400 or image.y_size < 400 | |
end | |
# Voila done! | |
end | |
def set_crop_and_rotate_parameters(x, y, w, h, rotation) | |
@crop_x = x | |
@crop_y = y | |
@crop_w = w | |
@crop_h = h | |
@rotate = rotation | |
end | |
def crop_image | |
image.recreate_versions! if crop_x.present? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment