This repository has been archived by the owner on Jul 13, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Extracting image dimensions
Eliot Sykes edited this page Mar 17, 2017
·
6 revisions
See https://github.com/teeparham/paperclip-meta
Image dimensions can be calculated and stored upon creating a file. In this case, we serialize image width and height into one field in the table: dimensions.
Asset.rb
# Table name: assets
#
# id :integer(4) not null, primary key
# upload_file_name :string(255) not null
# upload_content_type :string(255)
# upload_file_size :integer(4) not null
# upload_updated_at :datetime
# dimensions :string(30)
has_attached_file :upload
before_save :extract_dimensions
serialize :dimensions
# Helper method to determine whether or not an attachment is an image.
# @note Use only if you have a generic asset-type model that can handle different file types.
def image?
upload_content_type =~ %r{^(image|(x-)?application)/(bmp|gif|jpeg|jpg|pjpeg|png|x-png)$}
end
private
# Retrieves dimensions for image assets
# @note Do this after resize operations to account for auto-orientation.
def extract_dimensions
return unless image?
tempfile = upload.queued_for_write[:original]
unless tempfile.nil?
geometry = Paperclip::Geometry.from_file(tempfile)
self.dimensions = [geometry.width.to_i, geometry.height.to_i]
end
end
AssetsController.rb
@asset = Asset.find(params[:id])
width, height = @asset.dimensions