1

SixLabors ImageSharp 的文档非常有限,而且大多数 google 搜索都指向 GitHub,这不是很有帮助。

如何上传.Mutate带有透明填充的jpg并将其保存为具有透明度的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>和一个路径......

4

1 回答 1

2

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

您可以在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());
}

此外,如果保存到流中。

img.SaveAsPng(path);
于 2019-11-08T06:05:31.700 回答