Permalink
Browse files

support proportionate scaling

  • Loading branch information...
1 parent 4e6c214 commit 2b8df95f79f452b444368e404498db990c02482a Doug McInnes committed May 11, 2012
Showing with 42 additions and 4 deletions.
  1. +20 −4 lib/fastimage_resize.rb
  2. +22 −0 test/test.rb
@@ -44,6 +44,8 @@ class FormatNotSupported < FastImageException # :nodoc:
#
# FastImage Resize can resize GIF, JPEG and PNG files.
#
+ # Giving a zero value for width or height causes the image to scale proportionately.
+ #
# === Example
#
# require 'fastimage_resize'
@@ -83,7 +85,7 @@ def self.resize(input, w, h, options={})
end
in_path = file_in.respond_to?(:path) ? file_in.path : file_in
-
+
fast_image.resize_image(in_path, file_out.to_s, w.to_i, h.to_i, type_index, jpeg_quality.to_i)
if file_in.respond_to?(:close)
@@ -122,13 +124,10 @@ def resize_image(filename_in, filename_out, w, h, image_type, jpeg_quality); end
in = fopen(filename_in, "rb");
if (!in) return Qnil;
- im_out = gdImageCreateTrueColor(w, h); /* must be truecolor */
switch(image_type) {
case 0: im_in = gdImageCreateFromJpeg(in);
break;
case 1: im_in = gdImageCreateFromPng(in);
- gdImageAlphaBlending(im_out, 0); /* handle transparency correctly */
- gdImageSaveAlpha(im_out, 1);
break;
case 2: im_in = gdImageCreateFromGif(in);
trans = gdImageGetTransparent(im_in);
@@ -150,6 +149,23 @@ def resize_image(filename_in, filename_out, w, h, image_type, jpeg_quality); end
break;
default: return Qnil;
}
+
+ if (w == 0 || h == 0) {
+ int originalWidth = gdImageSX(im_in);
+ int originalHeight = gdImageSY(im_in);
+ if (w == 0) {
+ w = (int)(h * originalWidth / originalHeight);
+ } else {
+ h = (int)(w * originalHeight / originalWidth);
+ }
+ }
+
+ im_out = gdImageCreateTrueColor(w, h); /* must be truecolor */
+
+ if (image_type == 1) {
+ gdImageAlphaBlending(im_out, 0); /* handle transparency correctly */
+ gdImageSaveAlpha(im_out, 1);
+ }
fclose(in);
View
@@ -136,4 +136,26 @@ def test_output_tempfile_has_right_extension
outfile = FastImage.resize(File.join(FixturePath, "test.png"), 200, 200)
assert outfile.path =~ /\.png$/
end
+
+ def test_zero_width_scales_proportionately
+ GoodFixtures.each do |fn, info|
+ File.open(File.join(FixturePath, fn)) do |io|
+ halfHeight = (info[1][1] / 2).round
+ outfile = FastImage.resize(io, 0, halfHeight)
+ newWidth = (halfHeight * info[1][0] / info[1][1]).round
+ assert_equal [newWidth, halfHeight], FastImage.size(outfile)
+ end
+ end
+ end
+
+ def test_zero_height_scales_proportionately
+ GoodFixtures.each do |fn, info|
+ File.open(File.join(FixturePath, fn)) do |io|
+ halfWidth = (info[1][0] / 2).round
+ outfile = FastImage.resize(io, halfWidth, 0)
+ newHeight = (halfWidth * info[1][1] / info[1][0]).round
+ assert_equal [halfWidth, newHeight], FastImage.size(outfile)
+ end
+ end
+ end
end

0 comments on commit 2b8df95

Please sign in to comment.