通过指定高度或宽度在ASP.NET C#中按比例调整图像大小

Ida*_*ter 1 c# asp.net resize image imageresizer

我需要一个允许我调整图像大小的代码,但具有以下功能:

1)上传时调整图像大小

2)通过指定高度或宽度按比例调整图像大小.

注意:

  • 应该在ASP.NET C#中完成

例如:函数应获得宽度或高度,并按给定高度或宽度按比例调整图像大小.假设图像是400(w)x100(h).我想告诉函数将图像调整到特定高度,比方说80px.该功能应按比例调整图像大小,同时将图像高度设置为80px和宽度.另一种选择是告诉函数宽度,比方说200px,函数应该将图像调整为200px宽度并相应地设置高度.

3)将图像保存到特定位置(路径).

4)功能可以使用上传的图像或指定图像路径.

5)我希望能够选择图像质量

6)只需要这个JPEG

有人可以帮我解决这个问题.谢谢.

Lil*_*ver 5

尽管您似乎应该能够复制并粘贴代码片段来执行此操作,但如果您正在构建自己的图像大小调整系统,则需要注意大量陷阱。最好使用经过验证、经过测试且受支持的开源库。

要直接从 HttpPostedFile 调整文件大小,请调用

ImageBuilder.Current.Build(httpPostedFile, "img.jpg", new ResizeSettings("width=200&quality=90"));
Run Code Online (Sandbox Code Playgroud)

要调整现有文件的大小,请调用

ImageBuilder.Current.Build("orig.jpg", "img.jpg", new ResizeSettings("width=200&quality=90"));
Run Code Online (Sandbox Code Playgroud)

ImageResizing.Net库是免费的,并获得MIT 许可(不用担心许可问题)。


Muh*_*nan 5

最后一天,我找到了imageresizer,它很棒.和良好的API.效果很好.从Visual Studio 2010 Extension Manager下载:http://nuget.org/.

在VS-2010中下载API的简单步骤:

1).安装扩展http://nuget.org/.

在此输入图像描述

3).查找并安装ImageResizing
在此输入图像描述

4).然后代码:(我在这里使用裁剪.你可以使用任何)imageresizing.net上的文档

string uploadFolder = Server.MapPath(Request.ApplicationPath + "images/");
FileUpload1.SaveAs(uploadFolder + FileUpload1.FileName);


//The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details.
ResizeSettings resizeCropSettings = new ResizeSettings("width=200&height=200&format=jpg&crop=auto");

//Generate a filename (GUIDs are safest).
string fileName = Path.Combine(uploadFolder, System.Guid.NewGuid().ToString());

//Let the image builder add the correct extension based on the output file type (which may differ).
fileName = ImageBuilder.Current.Build(uploadFolder + FileUpload1.FileName, fileName, resizeCropSettings, false, true);
Run Code Online (Sandbox Code Playgroud)

尝试!!!它非常棒且易于使用.谢谢.


sta*_*247 5

从这个 Stackoverflow答案中,我得出:

public static Image Resize(this Image image, int maxWidth = 0, int maxHeight = 0)
    {
        if (maxWidth == 0)
            maxWidth = image.Width;
        if (maxHeight == 0)
            maxHeight = image.Height;

        var ratioX = (double)maxWidth / image.Width;
        var ratioY = (double)maxHeight / image.Height;
        var ratio = Math.Min(ratioX, ratioY);

        var newWidth = (int)(image.Width * ratio);
        var newHeight = (int)(image.Height * ratio);

        var newImage = new Bitmap(newWidth, newHeight);
        Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
        return newImage;
    }
Run Code Online (Sandbox Code Playgroud)

要调整图像大小并指定其 maxWidth:

var _image = Image.FromStream(Source);
var _thumbImage = _image.Resize(100);
Run Code Online (Sandbox Code Playgroud)

要调整图像大小并指定其 maxHeight:

var _image = Image.FromStream(Source);
var _thumbImage = _image.Resize(maxHeight: 100);
Run Code Online (Sandbox Code Playgroud)