Skip to content

Commit

Permalink
Merge pull request #2673 from tvdeyen/do-not-remove-background-from-n…
Browse files Browse the repository at this point in the history
…on-transparent-images

Do not remove background from non transparent images
  • Loading branch information
tvdeyen authored Jan 8, 2024
2 parents 4256c1b + c31b0fd commit b068ac6
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
5 changes: 4 additions & 1 deletion app/models/alchemy/picture_variant.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class PictureVariant
include Alchemy::Picture::Transformations

ANIMATED_IMAGE_FORMATS = %w[gif webp]
TRANSPARENT_IMAGE_FORMATS = %w[gif webp png]

attr_reader :picture, :render_format

Expand Down Expand Up @@ -100,7 +101,9 @@ def encoded_image(image, options = {})
end

if options[:flatten]
encoding_options << "-background transparent" if render_format == "png"
if render_format.in?(TRANSPARENT_IMAGE_FORMATS) && picture.image_file_format.in?(TRANSPARENT_IMAGE_FORMATS)
encoding_options << "-background transparent"
end
encoding_options << "-flatten"
end

Expand Down
2 changes: 2 additions & 0 deletions config/locales/alchemy.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,9 @@ en:
gif: GIF Image
jpeg: JPG Image
png: PNG Image
svg: SVG Image
tiff: TIFF Image
webp: WebP Image
misc:
name: Miscellaneous
values:
Expand Down
31 changes: 31 additions & 0 deletions spec/models/alchemy/picture_variant_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,37 @@
expect(step.arguments).to eq(["png", "-background transparent -flatten"])
end

context "converted to non transparent format" do
let(:options) do
{format: "jpg"}
end

it "does not add transparent background." do
step = subject.steps[0]
expect(step.name).to eq(:encode)
expect(step.arguments).to eq(["jpg", "-quality 85 -flatten"])
end
end

context "converted from non transparent format" do
let(:options) do
{format: "png", flatten: true}
end

let(:image_file) do
fixture_file_upload(
File.expand_path("../../fixtures/image4.jpg", __dir__),
"image/jpeg"
)
end

it "does not add transparent background." do
step = subject.steps[0]
expect(step.name).to eq(:encode)
expect(step.arguments).to eq(["png", "-flatten"])
end
end

context "converted to webp" do
let(:options) do
{format: "webp"}
Expand Down

0 comments on commit b068ac6

Please sign in to comment.