ASP.Net MVC 图片上传:通过缩小或填充调整大小

4
用户将能够上传图像。如果图像超过设定的大小,我希望将其缩小到该大小。显然,由于比例不匹配,宽度将是关键尺寸,因此高度将是可变的。
如果图像小于设置的大小,我想创建一个新图像,其大小为设置的大小,背景为定义的颜色,并将上传的图像居中放置在其中,因此结果是具有填充颜色的原始图像。
非常感谢任何代码示例或链接。

1
只需使用这个库的一行代码,就能将图片缩小到指定的宽度(如果原始图片比指定宽度大),或者扩展画布(如果原始图片比指定宽度小)。ImageBuilder.Current.Build(postedFile, destination, new ResizeSettings("width=500&scale=upscalecanvas&bgcolor=green")); 这里有一个实时例子 - Lilith River
2个回答

10

这是我快速编写的一小段调整大小代码,基于宽度进行调整。我相信你可以想出如何向位图添加背景颜色。这不是完整的代码,只是一个做事情的想法。

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

4
需要异常处理和JPEG编码设置...http://nathanaeljones.com/163/20-image-resizing-pitfalls/ - Lilith River

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接