Skip to content

A platform for community discussion. Free, open, simple.

DEV: Add support for cropping/resizing optimized images with DiscourseVips (#43466)

Alan Guo Xiang Tanff6a1d541254
diff --git a/app/models/optimized_image.rb b/app/models/optimized_image.rb
index bd34bfcf33f..2fc44f4e953 100644
--- a/app/models/optimized_image.rb
+++ b/app/models/optimized_image.rb
@@ -325,12 +325,70 @@ class OptimizedImage < ActiveRecord::Base
end
def self.resize(from, to, width, height, opts = {})
- optimize(:optimized_image_resize, from, to, "#{width}x#{height}", opts)
+ if GlobalSetting.enable_vips_image_processing
+ ensure_safe_paths!(from, to)
+ resize_with_vips(from: from, to: to, width: width, height: height, opts: opts)
+ else
+ optimize(:optimized_image_resize, from, to, "#{width}x#{height}", opts)
+ end
+ end
+
+ def self.resize_with_vips(from:, to:, width:, height:, opts:)
+ DiscourseVips.thumbnail(
+ input_path: from,
+ output_path: to,
+ input_format: image_extension(path: from, ext_path: to, opts: opts),
+ output_format: image_extension(path: to, ext_path: to, opts: opts),
+ width: width,
+ height: height,
+ size: :both,
+ crop: :centre,
+ sharpen: true,
+ operation: :optimized_image_resize,
+ quality: opts[:quality],
+ strip_metadata: SiteSetting.strip_image_metadata,
+ timeout: MAX_CONVERT_SECONDS,
+ read: [from],
+ write: [File.dirname(to)],
+ )
+ optimize_image(to: to)
+ rescue => error
+ handle_optimization_error(error: error, to: to, opts: opts)
end
+ private_class_method :resize_with_vips
def self.crop(from, to, width, height, opts = {})
- optimize(:optimized_image_crop, from, to, "#{width}x#{height}", opts)
+ if GlobalSetting.enable_vips_image_processing
+ ensure_safe_paths!(from, to)
+ crop_with_vips(from: from, to: to, width: width, height: height, opts: opts)
+ else
+ optimize(:optimized_image_crop, from, to, "#{width}x#{height}", opts)
+ end
+ end
+
+ def self.crop_with_vips(from:, to:, width:, height:, opts:)
+ DiscourseVips.thumbnail(
+ input_path: from,
+ output_path: to,
+ input_format: image_extension(path: from, ext_path: to, opts: opts),
+ output_format: image_extension(path: to, ext_path: to, opts: opts),
+ width: width,
+ height: height,
+ crop: :all,
+ gravity: :north,
+ sharpen: true,
+ operation: :optimized_image_crop,
+ quality: opts[:quality],
+ strip_metadata: SiteSetting.strip_image_metadata,
+ timeout: MAX_CONVERT_SECONDS,
+ read: [from],
+ write: [File.dirname(to)],
+ )
+ optimize_image(to: to)
+ rescue => error
+ handle_optimization_error(error: error, to: to, opts: opts)
end
+ private_class_method :crop_with_vips
def self.downsize(from:, to:, scale: nil, width: nil, height: nil, max_pixels: nil, **opts)
if GlobalSetting.enable_vips_image_processing
@@ -358,13 +416,18 @@ class OptimizedImage < ActiveRecord::Base
end
def self.downsize_with_vips(from:, to:, scale:, width:, height:, max_pixels:, opts:)
- DiscourseVips.downsize(
+ DiscourseVips.thumbnail(
input_path: from,
output_path: to,
+ input_format: image_extension(path: from, ext_path: to, opts: opts),
+ output_format: image_extension(path: to, ext_path: to, opts: opts),
scale: scale,
width: width,
height: height,
max_pixels: max_pixels,
+ size: width ? :down : :both,
+ sharpen: true,
+ operation: :optimized_image_downsize,
strip_metadata: SiteSetting.strip_image_metadata,
timeout: MAX_CONVERT_SECONDS,
read: [from],
diff --git a/lib/discourse_vips.rb b/lib/discourse_vips.rb
index 2c50cbe3c97..cdd79f68e3e 100644
--- a/lib/discourse_vips.rb
+++ b/lib/discourse_vips.rb
@@ -107,16 +107,24 @@ module DiscourseVips
)
end
- def self.downsize(
+ def self.thumbnail(
input_path:,
output_path:,
timeout:,
read:,
write:,
- scale: nil,
+ operation:,
+ input_format: nil,
+ output_format: nil,
width: nil,
height: nil,
+ scale: nil,
max_pixels: nil,
+ size: :both,
+ crop: :none,
+ gravity: nil,
+ sharpen: false,
+ quality: nil,
strip_metadata: false
)
if [scale, width || height, max_pixels].compact.length != 1 || width.nil? != height.nil?
@@ -124,33 +132,35 @@ module DiscourseVips
"provide exactly one resize target: scale, width and height, or max_pixels"
end
- format = File.extname(input_path).delete_prefix(".").downcase
- raise ArgumentError, "unsupported format" if !%w[jpg jpeg png gif webp avif].include?(format)
-
- output_mode =
- File.exist?(output_path) ? File.stat(output_path).mode & 0o777 : 0o666 & ~File.umask
-
- Tempfile.create(["downsize-", ".#{format}"], File.dirname(output_path)) do |output|
+ Tempfile.create(
+ ["thumbnail-", File.extname(output_path)],
+ File.dirname(output_path),
+ ) do |output|
output.close
Client.call(
[
- "downsize",
+ "thumbnail",
input_path,
output.path,
- format,
- scale,
width,
height,
+ scale,
max_pixels,
+ size,
+ crop,
+ sharpen,
+ quality,
strip_metadata,
+ gravity,
+ input_format,
+ output_format,
],
- operation: :optimized_image_downsize,
+ operation:,
read:,
write:,
timeout:,
nice: 10,
)
- File.chmod(output_mode, output.path)
File.rename(output.path, output_path)
end
nil
diff --git a/script/discourse_vips_worker b/script/discourse_vips_worker
index c7b39dea5dc..31d89e9e136 100644
--- a/script/discourse_vips_worker
+++ b/script/discourse_vips_worker
@@ -26,7 +26,7 @@ class DiscourseVipsWorker
DYNAMIC_LINKER_CACHE_PATH = "/etc/ld.so.cache"
private_constant :DYNAMIC_LINKER_CACHE_PATH
- WARM_OPERATIONS = %w[text gravity flatten pngsave thumbnail].freeze
+ WARM_OPERATIONS = %w[text gravity flatten pngsave thumbnail sharpen].freeze
private_constant :WARM_OPERATIONS
SVG_DIMENSIONS_RLIMITS = { cpu_seconds: 1, memory_bytes: 1024 * 1024 * 1024 }.freeze
@@ -73,17 +73,22 @@ class DiscourseVipsWorker
reencode_jpeg(input_path: arguments[0], output_path: arguments[1], quality: arguments[2])
when "svg-to-png"
svg_to_png(input_path: arguments[0], output_path: arguments[1])
-
- when "downsize"
- downsize(
+ when "thumbnail"
+ thumbnail(
input_path: arguments[0],
output_path: arguments[1],
- format: arguments[2],
- scale: arguments[3],
- width: arguments[4],
- height: arguments[5],
- max_pixels: arguments[6],
- strip_metadata: arguments[7],
+ width: arguments[2],
+ height: arguments[3],
+ scale: arguments[4],
+ max_pixels: arguments[5],
+ size: arguments[6],
+ crop: arguments[7],
+ sharpen: arguments[8],
+ quality: arguments[9],
+ strip_metadata: arguments[10],
+ gravity: arguments[11],
+ input_format: arguments[12],
+ output_format: arguments[13],
)
else
raise ArgumentError, "unsupported libvips operation"
@@ -291,65 +296,101 @@ class DiscourseVipsWorker
end
private_class_method :svg_to_png
- def self.downsize(
+ def self.thumbnail(
input_path:,
output_path:,
- format:,
- scale:,
width:,
height:,
+ scale:,
max_pixels:,
- strip_metadata:
+ size:,
+ crop:,
+ sharpen:,
+ quality:,
+ strip_metadata:,
+ gravity:,
+ input_format:,
+ output_format:
)
new do
- begin
- if !%w[true false].include?(strip_metadata)
- raise ArgumentError, "invalid metadata stripping flag"
- end
+ if !%w[true false].include?(sharpen)
+ raise ArgumentError, "invalid sharpening flag"
+ end
+ if !%w[true false].include?(strip_metadata)
+ raise ArgumentError, "invalid metadata stripping flag"
+ end
+ quality = quality.empty? ? nil : Integer(quality)
+
+ loaders = {
+ "jpg" => "VipsForeignLoadJpeg",
+ "jpeg" => "VipsForeignLoadJpeg",
+ "png" => "VipsForeignLoadPng",
+ "gif" => "VipsForeignLoadNsgif",
+ "webp" => "VipsForeignLoadWebp",
+ "avif" => "VipsForeignLoadHeif",
+ }
+ allowed = loaders.values
+ if !input_format.empty?
loader =
- {
- "jpg" => "VipsForeignLoadJpeg",
- "jpeg" => "VipsForeignLoadJpeg",
- "png" => "VipsForeignLoadPng",
- "gif" => "VipsForeignLoadNsgif",
- "webp" => "VipsForeignLoadWebp",
- "avif" => "VipsForeignLoadHeif",
- }.fetch(format) { raise ArgumentError, "unsupported input format" }
- block_loaders(allowed: [loader])
-
- if !width.empty? && !height.empty?
- width = Integer(width)
- height = Integer(height)
- raise ArgumentError, "invalid resize bounds" if !width.positive? || !height.positive?
-
- image =
- Vips::Image.thumbnail(input_path, width, height:, size: :down, output_profile: "srgb")
- else
- source = Vips::Image.new_from_file(input_path)
- scale =
- if max_pixels.empty?
- Float(scale)
- else
- Math.sqrt(Integer(max_pixels).fdiv(source.width * source.height))
- end
- raise ArgumentError, "invalid resize scale" if !scale.finite? || !scale.positive?
-
- edge = [([source.width, source.height].max * scale).round, 1].max
- image = Vips::Image.thumbnail(input_path, edge, output_profile: "srgb")
+ loaders.fetch(input_format.downcase) do
+ raise ArgumentError, "unsupported input format"
+ end
+ allowed = [loader]
+ end
+ block_loaders(allowed: allowed)
+
+ source =
+ begin
+ Vips::Image.new_from_file(input_path)
+ rescue Vips::Error => error
+ raise InvalidImage, error.message
end
- options = { strip: strip_metadata == "true" }
- options[:interlace] = false if %w[.jpg .jpeg .png .gif].include?(
- File.extname(output_path),
+ if !width.empty? && !height.empty?
+ width = Integer(width)
+ height = Integer(height)
+ else
+ scale =
+ if max_pixels.empty?
+ Float(scale)
+ else
+ max_pixels = Integer(max_pixels)
+ raise ArgumentError, "invalid resize scale" if !max_pixels.positive?
+
+ Math.sqrt(max_pixels.fdiv(source.width * source.height))
+ end
+ raise ArgumentError, "invalid resize scale" if !scale.finite? || !scale.positive?
+
+ width = [([source.width, source.height].max * scale).round, 1].max
+ height = width
+ end
+
+ image =
+ Vips::Image.thumbnail(
+ input_path,
+ width,
+ height: height,
+ size: size.to_sym,
+ crop: crop.to_sym,
+ output_profile: "srgb",
)
+ image = image.gravity(gravity.to_sym, width, height) if !gravity.empty?
+ image = image.sharpen if sharpen == "true"
+ options = { strip: strip_metadata == "true" }
+ options[:Q] = quality if quality
+ if output_format.empty?
image.write_to_file(output_path, **options)
- rescue Vips::Error => error
- raise InvalidImage, error.message
+ else
+ image.write_to_target(
+ Vips::Target.new_to_file(output_path),
+ ".#{output_format.downcase}",
+ **options,
+ )
end
nil
end
end
- private_class_method :downsize
+ private_class_method :thumbnail
def self.normalize_color(image)
image = image.colourspace(:srgb)
diff --git a/spec/lib/discourse_vips/downsize_spec.rb b/spec/lib/discourse_vips/downsize_spec.rb
deleted file mode 100644
index 9a2e5d8d379..00000000000
--- a/spec/lib/discourse_vips/downsize_spec.rb
+++ /dev/null
@@ -1,134 +0,0 @@
-# frozen_string_literal: true
-
-RSpec.describe DiscourseVips do
- describe ".downsize" do
- let(:directory) { Dir.mktmpdir }
- let(:input_path) { File.join(directory, "source.png") }
- let(:output_path) { File.join(directory, "output.png") }
-
- after { FileUtils.remove_entry(directory) }
-
- it "scales an image by the requested factor" do
- FileUtils.cp(file_from_fixtures("logo.png").path, input_path)
- output_path = File.join(directory, "output")
-
- described_class.downsize(
- input_path:,
- output_path:,
- scale: 0.5,
- timeout: 20,
- read: [input_path],
- write: [directory],
- )
-
- expect(FastImage.size(output_path)).to eq([122, 33])
- expect(FastImage.type(output_path)).to eq(:png)
- end
-
- it "rejects an image disguised as another format" do
- input_path = file_from_fixtures("svg.png").path
-
- expect {
- described_class.downsize(
- input_path:,
- output_path:,
- scale: 0.5,
- timeout: 20,
- read: [input_path],
- write: [directory],
- )
- }.to raise_error(DiscourseVips::InvalidImage)
-
- expect(File).not_to exist(output_path)
- end
-
- it "rejects an unsupported format" do
- input_path = File.join(directory, "source.ico")
-
- expect {
- described_class.downsize(
- input_path:,
- output_path:,
- scale: 0.5,
- timeout: 20,
- read: [input_path],
- write: [directory],
- )
- }.to raise_error(ArgumentError, "unsupported format")
- end
-
- it "rejects conflicting resize targets" do
- input_path = file_from_fixtures("logo.png").path
-
- expect {
- described_class.downsize(
- input_path:,
- output_path:,
- scale: 0.5,
- width: 100,
- height: 100,
- timeout: 20,
- read: [input_path],
- write: [directory],
- )
- }.to raise_error(
- ArgumentError,
- "provide exactly one resize target: scale, width and height, or max_pixels",
- )
- end
-
- it "reports invalid bounds as an operation error" do
- FileUtils.cp(file_from_fixtures("logo.png").path, input_path)
-
- expect {
- described_class.downsize(
- input_path:,
- output_path:,
- width: 0,
- height: 100,
- timeout: 20,
- read: [input_path],
- write: [directory],
- )
- }.to raise_error(DiscourseVips::Error, "invalid resize bounds")
- end
-
- it "reports an invalid scale as an operation error" do
- FileUtils.cp(file_from_fixtures("logo.png").path, input_path)
-
- expect {
- described_class.downsize(
- input_path:,
- output_path:,
- scale: 0,
- timeout: 20,
- read: [input_path],
- write: [directory],
- )
- }.to raise_error(DiscourseVips::Error, "invalid resize scale")
- end
-
- it "preserves the destination and removes temporary files when decoding fails" do
- File.binwrite(input_path, "invalid image")
- original_content = "original destination"
- File.binwrite(output_path, original_content)
-
- expect {
- described_class.downsize(
- input_path:,
- output_path:,
- scale: 0.5,
- timeout: 20,
- read: [input_path],
- write: [directory],
- )
- }.to raise_error(DiscourseVips::InvalidImage)
-
- expect(File.binread(output_path)).to eq(original_content)
- expect(Dir.children(directory)).to contain_exactly(
- File.basename(input_path),
- File.basename(output_path),
- )
- end
- end
-end
diff --git a/spec/lib/discourse_vips_spec.rb b/spec/lib/discourse_vips_spec.rb
index 3f3d51784c1..0270d1afa2f 100644
--- a/spec/lib/discourse_vips_spec.rb
+++ b/spec/lib/discourse_vips_spec.rb
@@ -783,4 +783,222 @@ RSpec.describe DiscourseVips do
end
end
end
+
+ describe ".thumbnail" do
+ let(:directory) { Dir.mktmpdir }
+ let(:input_path) { File.join(directory, "source.jpg") }
+ let(:output_path) { File.join(directory, "output.png") }
+
+ before { FileUtils.cp(file_from_fixtures("logo.png").path, input_path) }
+
+ after { FileUtils.remove_entry(directory) }
+
+ it "resizes an image using its contents instead of its input extension" do
+ described_class.thumbnail(
+ input_path: input_path,
+ output_path: output_path,
+ width: 100,
+ height: 50,
+ crop: :centre,
+ sharpen: true,
+ timeout: 10,
+ operation: :optimized_image_resize,
+ read: [input_path],
+ write: [directory],
+ )
+
+ expect(FastImage.size(output_path)).to eq([100, 50])
+ expect(FastImage.type(output_path)).to eq(:png)
+ end
+
+ it "uses format hints to write PNG data to a .bin output path" do
+ destination_path = File.join(directory, "output.bin")
+
+ described_class.thumbnail(
+ input_path: input_path,
+ output_path: destination_path,
+ input_format: "png",
+ output_format: "png",
+ width: 100,
+ height: 50,
+ crop: :centre,
+ timeout: 10,
+ operation: :optimized_image_resize,
+ read: [input_path],
+ write: [directory],
+ )
+
+ expect(FastImage.size(destination_path)).to eq([100, 50])
+ expect(FastImage.type(destination_path)).to eq(:png)
+ end
+
+ it "rejects PNG data when the input format hint is JPEG" do
+ expect {
+ described_class.thumbnail(
+ input_path: input_path,
+ output_path: output_path,
+ input_format: "jpg",
+ width: 100,
+ height: 50,
+ timeout: 10,
+ operation: :optimized_image_resize,
+ read: [input_path],
+ write: [directory],
+ )
+ }.to raise_error(DiscourseVips::InvalidImage)
+ end
+
+ it "rejects an input format outside the raster loader allowlist" do
+ expect {
+ described_class.thumbnail(
+ input_path: input_path,
+ output_path: output_path,
+ input_format: "svg",
+ width: 100,
+ height: 50,
+ timeout: 10,
+ operation: :optimized_image_resize,
+ read: [input_path],
+ write: [directory],
+ )
+ }.to raise_error(DiscourseVips::Error, "unsupported input format")
+ end
+
+ it "rejects unsupported output extensions" do
+ expect {
+ described_class.thumbnail(
+ input_path: input_path,
+ output_path: File.join(directory, "output.svg"),
+ width: 100,
+ height: 50,
+ timeout: 10,
+ operation: :optimized_image_resize,
+ read: [input_path],
+ write: [directory],
+ )
+ }.to raise_error(DiscourseVips::Error)
+ end
+
+ it "reports a quality option unsupported by the output encoder as an operation error" do
+ expect {
+ described_class.thumbnail(
+ input_path: input_path,
+ output_path: File.join(directory, "output.gif"),
+ width: 100,
+ height: 50,
+ quality: 75,
+ timeout: 10,
+ operation: :optimized_image_resize,
+ read: [input_path],
+ write: [directory],
+ )
+ }.to raise_error(DiscourseVips::Error)
+ end
+
+ it "reports invalid thumbnail options as an operation error" do
+ expect {
+ described_class.thumbnail(
+ input_path: input_path,
+ output_path: output_path,
+ width: 100,
+ height: 50,
+ size: :invalid,
+ timeout: 10,
+ operation: :optimized_image_resize,
+ read: [input_path],
+ write: [directory],
+ )
+ }.to raise_error(
+ DiscourseVips::Error,
+ "ruby-vips: enum 'VipsSize' has no member 'invalid', should be one of: both, up, down, force\n",
+ )
+ end
+
+ it "preserves the destination and removes temporary files after a decode error" do
+ File.binwrite(input_path, "invalid image")
+ File.binwrite(output_path, "existing destination")
+
+ expect {
+ described_class.thumbnail(
+ input_path: input_path,
+ output_path: output_path,
+ width: 100,
+ height: 50,
+ timeout: 10,
+ operation: :optimized_image_resize,
+ read: [input_path],
+ write: [directory],
+ )
+ }.to raise_error(DiscourseVips::InvalidImage)
+
+ expect(File.binread(output_path)).to eq("existing destination")
+ expect(Dir.children(directory)).to contain_exactly("source.jpg", "output.png")
+ end
+
+ it "rejects an SVG disguised as a PNG" do
+ FileUtils.cp(file_from_fixtures("svg.png").path, input_path)
+
+ expect {
+ described_class.thumbnail(
+ input_path: input_path,
+ output_path: output_path,
+ width: 100,
+ height: 50,
+ timeout: 10,
+ operation: :optimized_image_resize,
+ read: [input_path],
+ write: [directory],
+ )
+ }.to raise_error(DiscourseVips::InvalidImage)
+ end
+
+ it "scales an image by the requested factor" do
+ described_class.thumbnail(
+ input_path:,
+ output_path:,
+ scale: 0.5,
+ sharpen: true,
+ timeout: 20,
+ operation: :optimized_image_downsize,
+ read: [input_path],
+ write: [directory],
+ )
+
+ expect(FastImage.size(output_path)).to eq([122, 33])
+ expect(FastImage.type(output_path)).to eq(:png)
+ end
+
+ it "rejects conflicting resize targets" do
+ expect {
+ described_class.thumbnail(
+ input_path:,
+ output_path:,
+ scale: 0.5,
+ width: 100,
+ height: 100,
+ timeout: 20,
+ operation: :optimized_image_downsize,
+ read: [input_path],
+ write: [directory],
+ )
+ }.to raise_error(
+ ArgumentError,
+ "provide exactly one resize target: scale, width and height, or max_pixels",
+ )
+ end
+
+ it "reports an invalid scale as an operation error" do
+ expect {
+ described_class.thumbnail(
+ input_path:,
+ output_path:,
+ scale: 0,
+ timeout: 20,
+ operation: :optimized_image_downsize,
+ read: [input_path],
+ write: [directory],
+ )
+ }.to raise_error(DiscourseVips::Error, "invalid resize scale")
+ end
+ end
end
diff --git a/spec/lib/upload_creator_spec.rb b/spec/lib/upload_creator_spec.rb
index b622678e306..b0c33852d38 100644
--- a/spec/lib/upload_creator_spec.rb
+++ b/spec/lib/upload_creator_spec.rb
@@ -33,6 +33,43 @@ RSpec.describe UploadCreator do
include_examples "animated upload preservation"
end
+ shared_examples "image extension correction" do
+ it "resizes PNG data with a .bin extension and stores it as a PNG" do
+ file = Tempfile.new(%w[upload .bin])
+ FileUtils.copy_file(file_from_fixtures("logo.png").path, file.path)
+
+ upload =
+ described_class.new(
+ file,
+ "wrong_upload.bin",
+ type: "avatar",
+ force_optimize: true,
+ ).create_for(user.id)
+
+ expect(upload).to be_persisted
+ expect(upload.original_filename).to eq("wrong_upload.png")
+ expect(upload.extension).to eq("png")
+ expect(FastImage.type(Discourse.store.path_for(upload))).to eq(:png)
+ expect(FastImage.size(Discourse.store.path_for(upload))).to eq(
+ [Discourse.avatar_sizes.max, Discourse.avatar_sizes.max],
+ )
+ ensure
+ file&.close!
+ end
+ end
+
+ context "when processing images with ImageMagick" do
+ before { global_setting :enable_vips_image_processing, false }
+
+ include_examples "image extension correction"
+ end
+
+ context "when processing images with libvips" do
+ before { global_setting :enable_vips_image_processing, true }
+
+ include_examples "image extension correction"
+ end
+
context "when the upload is an SVG" do
before { SiteSetting.authorized_extensions = "svg" }
diff --git a/spec/models/optimized_image_spec.rb b/spec/models/optimized_image_spec.rb
index 639ada9e50a..bb8377611d7 100644
--- a/spec/models/optimized_image_spec.rb
+++ b/spec/models/optimized_image_spec.rb
@@ -8,6 +8,55 @@ RSpec.describe OptimizedImage do
before { upload.id = 42 }
describe ".crop" do
+ let(:directory) { Dir.mktmpdir }
+ let(:input_path) { File.join(directory, "source.png") }
+
+ before { FileUtils.cp(file_from_fixtures("logo.png").path, input_path) }
+
+ after { FileUtils.remove_entry(directory) }
+
+ shared_examples "crop processing" do
+ it "crops an image in place" do
+ result = described_class.crop(input_path, input_path, 100, 50)
+
+ expect(result).to eq(true)
+ expect(FastImage.size(input_path)).to eq([100, 50])
+ end
+
+ it "crops vertical content from the top edge" do
+ FileHelper.stubs(:optimize_image!).returns(true)
+
+ Dir.mktmpdir do |directory|
+ output_path = File.join(directory, "cropped.png")
+
+ described_class.crop(
+ Rails.root.join("spec/fixtures/images/crop_position.png").to_s,
+ output_path,
+ 3,
+ 2,
+ )
+ output_image = ChunkyPNG::Image.from_file(output_path)
+
+ expect([output_image.width, output_image.height]).to eq([3, 2])
+ expect(output_image.pixels).to all(
+ satisfy { |pixel| ChunkyPNG::Color.r(pixel) > ChunkyPNG::Color.b(pixel) },
+ )
+ end
+ end
+ end
+
+ context "with libvips disabled" do
+ before { global_setting :enable_vips_image_processing, false }
+
+ include_examples "crop processing"
+ end
+
+ context "with libvips enabled" do
+ before { global_setting :enable_vips_image_processing, true }
+
+ include_examples "crop processing"
+ end
+
it "produces cropped images with ImageMagick 7" do
tmp_path = "/tmp/cropped.png"
desired_width = 5
@@ -33,27 +82,6 @@ RSpec.describe OptimizedImage do
end
end
- it "crops vertical content from the top edge" do
- FileHelper.stubs(:optimize_image!).returns(true)
-
- Dir.mktmpdir do |directory|
- output_path = File.join(directory, "cropped.png")
-
- described_class.crop(
- Rails.root.join("spec/fixtures/images/crop_position.png").to_s,
- output_path,
- 3,
- 2,
- )
- output_image = ChunkyPNG::Image.from_file(output_path)
-
- expect([output_image.width, output_image.height]).to eq([3, 2])
- expect(output_image.pixels).to all(
- satisfy { |pixel| ChunkyPNG::Color.r(pixel) > ChunkyPNG::Color.b(pixel) },
- )
- end
- end
-
it "crops images horizontally" do
tmp_path = "/tmp/cropped.png"
desired_width = 244
@@ -89,28 +117,29 @@ RSpec.describe OptimizedImage do
expect(instructions).to include("-colors")
end
end
+ end
- describe ".resize" do
- it "handles an invalid extension" do
- original_path = Dir::Tmpname.create(%w[origin .bin]) { nil }
-
- begin
- FileUtils.cp "#{Rails.root.join("spec/fixtures/images/logo.png")}", original_path
+ describe ".resize" do
+ let(:directory) { Dir.mktmpdir }
+ let(:input_path) { File.join(directory, "source.png") }
- # we use "filename" to get the correct extension here, it is more important
- # then any other param
+ before { FileUtils.cp(file_from_fixtures("logo.png").path, input_path) }
- orig_size = File.size(original_path)
+ after { FileUtils.remove_entry(directory) }
- OptimizedImage.resize(original_path, original_path, 5, 5, filename: "test.png")
+ shared_examples "resize processing" do
+ it "resizes an image in place" do
+ result = described_class.resize(input_path, input_path, 100, 50)
- new_size = File.size(original_path)
- expect(orig_size).to be > new_size
- expect(new_size).not_to eq(0)
- ensure
- File.delete(original_path) if File.exist?(original_path)
- end
+ expect(result).to eq(true)
+ expect(FastImage.size(input_path)).to eq([100, 50])
end
+ end
+
+ context "with libvips disabled" do
+ before { global_setting :enable_vips_image_processing, false }
+
+ include_examples "resize processing"
it "optimizes the image" do
file = File.open("#{Rails.root.join("spec/fixtures/images/resized.png")}")
@@ -143,26 +172,30 @@ RSpec.describe OptimizedImage do
expect(thumb.filesize).to be > 200
end
- describe "when an svg with a href is masked as a png" do
- it "does not trigger an external request" do
- tmp_path = "/tmp/resized.png"
-
- begin
- expect do
- OptimizedImage.resize(
- "#{Rails.root.join("spec/fixtures/images/svg.png")}",
- tmp_path,
- 5,
- 5,
- raise_on_error: true,
- )
- end.to raise_error(RuntimeError, /improper image header/)
- ensure
- File.delete(tmp_path) if File.exist?(tmp_path)
- end
+ it "rejects an SVG disguised as a PNG" do
+ tmp_path = "/tmp/resized.png"
+
+ begin
+ expect do
+ OptimizedImage.resize(
+ "#{Rails.root.join("spec/fixtures/images/svg.png")}",
+ tmp_path,
+ 5,
+ 5,
+ raise_on_error: true,
+ )
+ end.to raise_error(Discourse::Utils::CommandError)
+ ensure
+ File.delete(tmp_path) if File.exist?(tmp_path)
end
end
end
+
+ context "with libvips enabled" do
+ before { global_setting :enable_vips_image_processing, true }
+
+ include_examples "resize processing"
+ end
end
describe ".downsize" do
diff --git a/spec/requests/user_avatars_controller_spec.rb b/spec/requests/user_avatars_controller_spec.rb
index 87b5bd93fd9..65533f3ca90 100644
--- a/spec/requests/user_avatars_controller_spec.rb
+++ b/spec/requests/user_avatars_controller_spec.rb
@@ -86,7 +86,7 @@ RSpec.describe UserAvatarsController do
end
describe "#show" do
- context "when invalid" do
+ shared_examples "avatar extension correction" do
after { FileUtils.rm(Discourse.store.path_for(upload)) }
let :upload do
@@ -102,7 +102,7 @@ RSpec.describe UserAvatarsController do
user
end
- it "automatically corrects bad avatar extensions" do
+ it "corrects a PNG avatar mislabeled as JPEG" do
orig = Discourse.store.path_for(upload)
upload.update_columns(
@@ -126,6 +126,18 @@ RSpec.describe UserAvatarsController do
end
end
+ context "when an avatar has an incorrect extension with libvips disabled" do
+ before { global_setting :enable_vips_image_processing, false }
+
+ include_examples "avatar extension correction"
+ end
+
+ context "when an avatar has an incorrect extension with libvips enabled" do
+ before { global_setting :enable_vips_image_processing, true }
+
+ include_examples "avatar extension correction"
+ end
+
it "serves sanitized SVG avatars without DTD entities" do
SiteSetting.authorized_extensions = "svg"
user = Fabricate(:user)