Search code examples
c#imagesharp

How to add transparent padding to a jpg and save it as png with transparency?


The documentation for SixLabors ImageSharp is very limited, and most google searches leads to GitHub, which is not very helpful.

How can I upload a jpg, .Mutate it with transparent padding and save it as a png with transparency?

This is the code I have so far. If the uploaded image is a png, transparent padding works, but jpgs get black padding:

private static void ResizeAndSavePhoto(Image<Rgba32> img, string path, int squareSize)
{
    Configuration.Default.ImageFormatsManager.SetEncoder(PngFormat.Instance, new PngEncoder()
    {
        ColorType = PngColorType.RgbWithAlpha
    });
    img.Mutate(x =>
        x.Resize(new ResizeOptions
        {
            Size = new Size(squareSize, squareSize),
            Mode = ResizeMode.Pad
        }).BackgroundColor(new Rgba32(255, 255, 255, 0))
        );
    img.Save(path);
    return;
}

.SaveAsPng() takes a filestream, but I have an Image<Rgba32> and a path...


Solution

  • You can explicitly save as a png via SaveAsPng, set the path extensions to .png, or pass an IImageEncoder to the Save methods.

    You'll find API docs at https://docs.sixlabors.com/api/index.html

    private static void ResizeAndSavePhoto(Image<Rgba32> img, string path, int squareSize)
    {
        img.Mutate(x =>
            x.Resize(new ResizeOptions
            {
                Size = new Size(squareSize, squareSize),
                Mode = ResizeMode.Pad
            }).BackgroundColor(new Rgba32(255, 255, 255, 0)));
    
        // The following demonstrates how to force png encoding with a path.
        img.Save(Path.ChangeExtension(path, ".jpg"))
    
        img.Save(path, new PngEncoder());
    }
    

    Additionally, if saving to a stream.

    img.SaveAsPng(path);