如何为jpg添加透明填充并将其另存为具有透明性的png? [英] How to add transparent padding to a jpg and save it as png with transparency?

查看:284
本文介绍了如何为jpg添加透明填充并将其另存为具有透明性的png?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SixLabors ImageSharp的文档非常有限,大多数Google搜索都指向GitHub,但这不是很有帮助.

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

如何上载jpg,.Mutate并使用透明填充并将其另存为png并具有透明性?

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

这是我到目前为止的代码.如果上传的图片是png,则可以使用透明填充,但是jpgs可以使用黑色填充:

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

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

推荐答案

您可以通过SaveAsPng明确地另存为png,将路径扩展名设置为.png,或将IImageEncoder传递给Save方法

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

您可以在 https://docs.sixlabors.com/api/中找到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);

这篇关于如何为jpg添加透明填充并将其另存为具有透明性的png?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆