diff --git a/lib/cooked_post_processor.rb b/lib/cooked_post_processor.rb index ea35cafc7..13d30c2c9 100644 --- a/lib/cooked_post_processor.rb +++ b/lib/cooked_post_processor.rb @@ -94,7 +94,20 @@ class CookedPostProcessor def get_size_from_attributes(img) w, h = img["width"].to_i, img["height"].to_i - return [w, h] if w > 0 && h > 0 + return [w, h] unless w <= 0 || h <= 0 + # if only width or height are specified attempt to scale image + if w > 0 || h > 0 + w = w.to_f + h = h.to_f + original_width, original_height = get_size(img["src"]).map {|integer| integer.to_f} + if w > 0 + ratio = w/original_width + return [w.floor, (original_height*ratio).floor] + else + ratio = h/original_height + return [(original_width*ratio).floor, h.floor] + end + end end def get_size_from_image_sizes(src, image_sizes) diff --git a/spec/components/cooked_post_processor_spec.rb b/spec/components/cooked_post_processor_spec.rb index 87e282ab5..683fdf855 100644 --- a/spec/components/cooked_post_processor_spec.rb +++ b/spec/components/cooked_post_processor_spec.rb @@ -182,6 +182,37 @@ describe CookedPostProcessor do end + context ".get_size_from_attributes" do + + let(:post) { build(:post) } + let(:cpp) { CookedPostProcessor.new(post) } + + it "returns the size when width and height are specified" do + img = { 'src' => 'http://foo.bar/image3.png', 'width' => 50, 'height' => 70} + expect(cpp.get_size_from_attributes(img)).to eq([50, 70]) + end + + it "returns the size when width and height are floats" do + img = { 'src' => 'http://foo.bar/image3.png', 'width' => 50.2, 'height' => 70.1} + expect(cpp.get_size_from_attributes(img)).to eq([50, 70]) + end + + it "resizes when only width is specified" do + img = { 'src' => 'http://foo.bar/image3.png', 'width' => 100} + SiteSetting.stubs(:crawl_images?).returns(true) + FastImage.expects(:size).returns([200, 400]) + expect(cpp.get_size_from_attributes(img)).to eq([100, 200]) + end + + it "resizes when only height is specified" do + img = { 'src' => 'http://foo.bar/image3.png', 'height' => 100} + SiteSetting.stubs(:crawl_images?).returns(true) + FastImage.expects(:size).returns([100, 300]) + expect(cpp.get_size_from_attributes(img)).to eq([33, 100]) + end + + end + context ".get_size_from_image_sizes" do let(:post) { build(:post) }