Commit d594746f by Ryan Sonnek Committed by Mike Burns

add Geometry#resize_to to calculate dimensions of new source

parent 5bf0619f
......@@ -101,6 +101,33 @@ module Paperclip
[ scale_geometry, crop_geometry ]
end
# resize to a new geometry
# @param geometry [String] the Paperclip geometry definition to resize to
# @example
# Paperclip::Geometry.new(150, 150).resize_to('50x50!')
# #=> Paperclip::Geometry(50, 50)
def resize_to(geometry)
new_geometry = Paperclip::Geometry.parse geometry
case new_geometry.modifier
when '!', '#'
new_geometry
when '>'
if new_geometry.width >= self.width && new_geometry.height >= self.height
self
else
scale_to new_geometry
end
when '<'
if new_geometry.width <= self.width || new_geometry.height <= self.height
self
else
scale_to new_geometry
end
else
scale_to new_geometry
end
end
private
def scaling dst, ratio
......@@ -118,5 +145,11 @@ module Paperclip
"%dx%d+%d+%d" % [ dst.width, dst.height, (self.width * scale - dst.width) / 2, 0 ]
end
end
# scale to the requested geometry and preserve the aspect ratio
def scale_to(new_geometry)
scale = [new_geometry.width.to_f / self.width.to_f , new_geometry.height.to_f / self.height.to_f].min
Paperclip::Geometry.new (self.width * scale).round, (self.height * scale).round
end
end
end
require 'rubygems'
require './test/helper'
class GeometryTest < Test::Unit::TestCase
......@@ -202,5 +203,24 @@ class GeometryTest < Test::Unit::TestCase
end
end
end
[['256x256', '150x150!' => [150, 150], '150x150#' => [150, 150], '150x150>' => [150, 150], '150x150<' => [256, 256], '150x150' => [150, 150]],
['256x256', '512x512!' => [512, 512], '512x512#' => [512, 512], '512x512>' => [256, 256], '512x512<' => [512, 512], '512x512' => [512, 512]],
['600x400', '512x512!' => [512, 512], '512x512#' => [512, 512], '512x512>' => [512, 341], '512x512<' => [600, 400], '512x512' => [512, 341]]].each do |original_size, options|
options.each_pair do |size, dimensions|
context "#{original_size} resize_to #{size}" do
setup do
@source = Paperclip::Geometry.parse original_size
@new_geometry = @source.resize_to size
end
should "have #{dimensions.first} width" do
assert_equal dimensions.first, @new_geometry.width
end
should "have #{dimensions.last} height" do
assert_equal dimensions.last, @new_geometry.height
end
end
end
end
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment