如何保持图像的宽高比时,使用asp:FileUpload (asp.Net - c#)
本文关键字:asp FileUpload Net 使用 图像 何保持 高比时 | 更新日期: 2023-09-27 18:07:56
这是我的aspx代码:
<asp:FileUpload ID="FileUpload2" runat="server" Width="500px" />
<asp:Button ID="btnUploadImg" runat="server" onclick="btnNahrajObrazek_Click" Text="Nahrát obrázek" Height="35px" Width="150px" />
,下面是我的代码:
protected void btnUploadImg_Click(object sender, EventArgs e)
{
string input = Request.Url.AbsoluteUri;
string output = input.Substring(input.IndexOf('=') + 1);
string fileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
int width = 800;
int height = 600;
Stream stream = FileUpload2.PostedFile.InputStream;
Bitmap image = new Bitmap(stream);
Bitmap target = new Bitmap(width, height);
Graphics graphic = Graphics.FromImage(target);
graphic.DrawImage(image, 0, 0, width, height);
target.Save(Server.MapPath("~/Uploads/" + output + "/") + fileName);
}
我想保持图像的长宽比上传,所以我只需要设置宽度或设置宽度如100%和高度400或类似的东西?但不知道该怎么做。
如果这是不可能的,图像裁剪将是足够好的,但我希望第一个更好。
提前感谢!
所以这是我的解决方案基于我在这里发现:http://www.nerdymusings.com/LPMArticle.asp?ID=32
string input = Request.Url.AbsoluteUri;
string output = input.Substring(input.IndexOf('=') + 1);
string fileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
Stream stream = FileUpload2.PostedFile.InputStream;
Bitmap sourceImage = new Bitmap(stream);
int maxImageWidth = 800;
if (sourceImage.Width > maxImageWidth)
{
int newImageHeight = (int)(sourceImage.Height * ((float)maxImageWidth / (float)sourceImage.Width));
Bitmap resizedImage = new Bitmap(maxImageWidth, newImageHeight);
Graphics gr = Graphics.FromImage(resizedImage);
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.DrawImage(sourceImage, 0, 0, maxImageWidth, newImageHeight);
// Save the resized image:
resizedImage.Save(Server.MapPath("~/Uploads/" + output + "/") + fileName);
}
else
{
sourceImage.Save(Server.MapPath("~/Uploads/" + output + "/") + fileName);
}