c# - ASP.Net MVC 图像上传通过缩小或填充调整大小

标签 c# asp.net asp.net-mvc image

用户将能够上传图片。如果图像大于设定尺寸,我想将其缩小到该尺寸。显然,由于比率,它不必完全匹配,宽度将是关键大小,因此高度将是可变的。

如果图像小于设置的尺寸,我想创建一个新图像,使其达到设置的尺寸,背景为定义的颜色,然后将上传的图像居中放置,因此结果是带有填充颜色的原始图像。

非常感谢任何代码示例或链接

最佳答案

这是我快速编写的一段代码,用于根据宽度调整它的大小。我相信您能弄清楚如何向位图添加背景颜色。它不是完整的代码,而只是关于如何做事的想法。

public static void ResizeLogo(string originalFilename, string resizeFilename)
{
    Image imgOriginal = Image.FromFile(originalFilename);

    //pass in whatever value you want for the width (180)
    Image imgActual = ScaleBySize(imgOriginal, 180);
    imgActual.Save(resizeFilename);
    imgActual.Dispose();
}

public static Image ScaleBySize(Image imgPhoto, int size)
{
    int logoSize = size;

    float sourceWidth = imgPhoto.Width;
    float sourceHeight = imgPhoto.Height;
    float destHeight = 0;
    float destWidth = 0;
    int sourceX = 0;
    int sourceY = 0;
    int destX = 0;
    int destY = 0;

    // Resize Image to have the height = logoSize/2 or width = logoSize.
    // Height is greater than width, set Height = logoSize and resize width accordingly
    if (sourceWidth > (2 * sourceHeight))
    {
        destWidth = logoSize;
        destHeight = (float)(sourceHeight * logoSize / sourceWidth);
    }
    else
    {
        int h = logoSize / 2;
        destHeight = h;
        destWidth = (float)(sourceWidth * h / sourceHeight);
    }
    // Width is greater than height, set Width = logoSize and resize height accordingly

    Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight, 
                                PixelFormat.Format32bppPArgb);
    bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

    grPhoto.DrawImage(imgPhoto,
        new Rectangle(destX, destY, (int)destWidth, (int)destHeight),
        new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight),
        GraphicsUnit.Pixel);

    grPhoto.Dispose();

    return bmPhoto;
}

关于c# - ASP.Net MVC 图像上传通过缩小或填充调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1007158/

相关文章:

c# - 将具有子实体的实体添加到 Redis 服务器导致 System.StackOverflowException

c# - 如何将 MailMesage 保存到 .msg 文件?

asp.net - ASP .NET MVC 在工作期间进行身份验证和保持用户身份验证的最佳实践

c# - 在 asp.net 中获取 Windows/域凭据,同时允许在 IIS 中进行匿名访问

c# - ASP.NET MVC 发布的实体未映射到 LINQ 模型

asp.net - 无效操作异常 : The partial view was not found. MVC3.1

c# - 调用有错误的存储过程,继续并获取完整输出

c# - 解析 XML 时处理速记结束标记

c# - 不可空类型

c# - 在 .net5/vNext/MVC6 中添加新的路由约束