SixLabors / ImageSharp

:camera: A modern, cross-platform, 2D Graphics library for .NET
https://sixlabors.com/products/imagesharp/
Other
7.34k stars 847 forks source link

Calling `Transform` using a `ProjectiveTransformBuilder` on a 32-bit image leaves black in the background instead of transparency #2616

Closed aceoft closed 9 months ago

aceoft commented 9 months ago

Prerequisites

ImageSharp version

3.1.1

Other ImageSharp packages and versions

None

Environment (Operating system, version and so on)

Win10 22H2

.NET Framework version

7/8

Description

In 3.0.2, when applying a taper or perspective transform to an Rgba32 image using the Transform method, the areas left behind are transparent. Starting in 3.1.0, they are black instead. Not sure if this can be called a bug, but it is a change in behavior, so I submit this issue for your consideration.

Steps to Reproduce

using var original = Image.Load<Rgb24>("numbered-grid.png");
using var converted = original.CloneAs<Rgba32>();

var inset = 60;
var builder = new ProjectiveTransformBuilder();
builder.AppendTaper(TaperSide.Top, TaperCorner.Both, 1 - (inset * 2 / (float)original.Width));

converted.Mutate(i => i.Transform(builder));
converted.SaveAsPng("v311.png");

Output in 3.0.2:

v302

Output in 3.1.0, 3.1.1:

v311

I noticed that loading up the source grid image in Photoshop also says 'Indexed Color' instead of RGB, so I converted it to RGB and tried again. Same black background, but now the output image is nearly 4x the size of the previous output (190KB vs 34KB), and RGB as well instead of indexed.

Images

Indexed: numbered-grid

RGB: numbered-grid-rgb

JimBobSquarePants commented 9 months ago

For the indexed version you need to delete the palette from the metadata.

PngMetadata metadata = converted.Metadata.GetPngMetadata();
metadata.ColorTable = null;

2616-i-out

For your Rgb version you would need to set the png metadata colortype to the following

PngMetadata metadata = converted.Metadata.GetPngMetadata();
metadata.ColorType = PngColorType.RgbWithAlpha;

2616-out

v3.1.0+ respects the metadata from the originally encoded image. You've introduced transparency where there wasn't previously so that metadata must be updated.

aceoft commented 9 months ago

I saw your response and was nearly there after digging through the metadata, but your edit really helped and I have it working again, thank you!

JimBobSquarePants commented 9 months ago

No worries. I want to see if I can improve this for V4 so we do the right thing more often.