Imagesharp: Converting Png to Jpg give a color background and not white (Asp.Net Core)

Created on 29 Sep 2017  路  3Comments  路  Source: SixLabors/ImageSharp

Description

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.

Steps to Reproduce

        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 :
2553905512_listing_logo

To :
2553905512_preview

if i save the outputstream as a jpg. the error occur. The image variable has also this background in color and not white.

System Configuration

  • ImageSharp version: 1.0.0-alpha9-00194
  • Environment (Operating system, version and so on): windows 10
  • .NET Framework version: .Net Standard 1.6

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).

image.Mutate(x => x.BackgroundColor(Rgba32.White));

Cheers

James

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings