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

↘锁芯ラ 提交于 2021-02-10 20:25:36

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/58643822/how-to-add-transparent-padding-to-a-jpg-and-save-it-as-png-with-transparency

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!