My goal is to generate renditions (thumbnail, and other size of the image) from an uploaded image (IFormFile, png or jpg).
When uploading a .png with transparency, the resulting image has a background of a color in the image and not a default white one.
public static Stream GenerateCompressedOriginal(IFormFile file)
{
Stream outputStream = new MemoryStream();
using (Image<Rgba32> image = Image.Load(file.OpenReadStream()))
{
image.SaveAsJpeg(outputStream, new JpegEncoder() { Quality = 80 });
}
return outputStream;
}
From :

To :

if i save the outputstream as a jpg. the error occur. The image variable has also this background in color and not white.
Hi @FelixLeChat ,
The transparent sections of the image are not actually fully transparent, rather only the alpha component of the pixels is set to zero.
You'll need to manually set the background color (Using the new beta API).
image.Mutate(x => x.BackgroundColor(Rgba32.White));
Cheers
James
I feel we should be doing this by default when encoding into formats that don't support alpha channels.
I think we should add a NormalizeBackground property onto JpegEncoder that, if enabled (defaulted to true), will do the background color fixes as it encodes each pixel.
I disagree. The encoding overheads in my opinion are too high and it's technically incorrect.
Adding the method to the consumers pipeline code is trivial. Consumers should know what they are operating on.
Most helpful comment
Hi @FelixLeChat ,
The transparent sections of the image are not actually fully transparent, rather only the alpha component of the pixels is set to zero.
You'll need to manually set the background color (Using the new beta API).
Cheers
James