简体   繁体   English

如何在.NET Core中使用MagickImage向图像添加填充

[英]How to add padding to an image using MagickImage in .NET core

I'm trying to write a function that adds padding to an image but I'm not sure on how to do that with ImageMagick. 我正在尝试编写一个向图像添加填充的函数,但是我不确定如何使用ImageMagick做到这一点。

    public bool AddPadding(string filePath)
    {
        // Read from file
        using (MagickImage image = new MagickImage(filePath))
        {
            int imageSize;
            int imageX = image.Width;
            int imageY = image.Height;

            if(imageX > imageY)
            {
                imageSize = imageX;
            }
            else
            {
                imageSize = imageY;
            }

            MagickGeometry size = new MagickGeometry(imageSize, imageSize);
            // Probably do more stuff here?




            // Save the result
            image.Write(filePath);
        }
    }

What do I need to add so that the image is centered and whitespace is added to both left and right? 我需要添加什么以便图像居中并在左右两侧都添加空格?

You can use the Extent method of MagickImage for this. 您可以为此使用MagickImageExtent方法。 Below is an example of how you could do that. 以下是如何执行此操作的示例。

public bool AddPadding(string filePath)
{
    // Read from file
    using (MagickImage image = new MagickImage(filePath))
    {
        int imageSize = Math.Max(image.Width, image.Height);

        // Add padding
        image.Extent(imageSize, imageSize, Gravity.Center, MagickColors.Purple);

        // Save the result
        image.Write(filePath);
    }
}

This adds a purple padding so you might want to change the color to a different one instead. 这会添加紫色填充,因此您可能需要将颜色更改为其他颜色。

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

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