繁体   English   中英

如何将透明填充添加到 jpg 并将其保存为具有透明度的 png?

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

SixLabors ImageSharp 的文档非常有限,大多数 google 搜索导致 GitHub,这不是很有帮助。

如何上传 jpg,使用透明填充对其进行.Mutate并将其保存为具有透明度的 png?

这是我到目前为止的代码。 如果上传的图像是 png,则透明填充有效,但 jpg 得到黑色填充:

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()需要一个文件流,但我有一个Image<Rgba32>和一个路径......

您可以通过SaveAsPng显式保存为 png,将路径扩展名设置为.png ,或将IImageEncoder传递给Save方法。

您可以在https://docs.sixlabors.com/api/index.html找到 API 文档

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

此外,如果保存到 stream。

img.SaveAsPng(path);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM