A platform for community discussion. Free, open, simple.
FIX: Keep image downsizing within the pixel limit (#43803)
Alan Guo Xiang Tanbdd1f6f2159c
diff --git a/script/discourse_vips_worker b/script/discourse_vips_workerindex 8e6d1c680df..b548c025039 100644--- a/script/discourse_vips_worker+++ b/script/discourse_vips_worker@@ -349,19 +349,25 @@ class DiscourseVipsWorkerwidth = Integer(width)height = Integer(height)else+ max_pixels = max_pixels.empty? ? nil : Integer(max_pixels)scale =- if max_pixels.empty?- Float(scale)- else- max_pixels = Integer(max_pixels)+ if max_pixelsraise ArgumentError, "invalid resize scale" if !max_pixels.positive?+ source = source.autorotMath.sqrt(max_pixels.fdiv(source.width * source.height))+ else+ Float(scale)endraise ArgumentError, "invalid resize scale" if !scale.finite? || !scale.positive?- width = [([source.width, source.height].max * scale).round, 1].max- height = width+ if max_pixels+ width = (source.width * scale).floor.clamp(1, max_pixels)+ height = (source.height * scale).floor.clamp(1, max_pixels)+ else+ width = [([source.width, source.height].max * scale).round, 1].max+ height = width+ endendimage =diff --git a/spec/lib/discourse_vips_spec.rb b/spec/lib/discourse_vips_spec.rbindex 7cd80dfb3eb..41f9812f51c 100644--- a/spec/lib/discourse_vips_spec.rb+++ b/spec/lib/discourse_vips_spec.rb@@ -991,6 +991,25 @@ RSpec.describe DiscourseVips doexpect(FastImage.type(output_path)).to eq(:png)end+ it "keeps resized images within the pixel limit" do+ [[301, 199, 4000], [199, 301, 4000], [301, 1, 1]].each do |width, height, max_pixels|+ ChunkyPNG::Image.new(width, height).save(input_path)++ described_class.thumbnail(+ input_path:,+ output_path:,+ max_pixels:,+ timeout: 20,+ operation: :optimized_image_downsize,+ read: [input_path],+ write: [directory],+ )++ output_width, output_height = FastImage.size(output_path)+ expect(output_width * output_height).to be <= max_pixels+ end+ end+it "rejects conflicting resize targets" doexpect {described_class.thumbnail(