gpt4 book ai didi

c# - 在 Asp Core 中上传时调整图像大小

转载 作者:行者123 更新时间:2023-11-30 15:14:05 24 4
gpt4 key购买 nike

在保存照片之前,当用户选择要上传的照片时,我需要更改照片的大小并将其保存为新的大小。

我使用此代码,但它不会以新尺寸保存。有什么问题 ?

public async Task<IActionResult> UploadNewsPic()
{
var file = Request.Form.Files[0];
try
{
if (file.Length > 0)
{
string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(_applicationRoot.UploadNewPath(), file.Name);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
if (file.IsImage())
{
await file.ResizeImage(3, 3);
file.CopyTo(stream);
}
}
}
return Ok();
}
catch (Exception e)
{
return BadRequest();
}
}

这是调整扩展:

 public async static Task<Image> ResizeImage(this IFormFile file, int width, int height)
{
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
using (var img = Image.FromStream(memoryStream))
{
return img.Resize(width, height);
}
}
}

public static Image Resize(this Image image, int width, int height)
{
var res = new Bitmap(width, height);
using (var graphic = Graphics.FromImage(res))
{
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.DrawImage(image, 0, 0, width, height);
}
return res;
}

最佳答案

您需要将 ResizeImage 的结果保存到流中。现在您只是复制原始文件。

var img = await file.ResizeImage(3, 3);
img.Save(stream, SomeFormat);

关于c# - 在 Asp Core 中上传时调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56163121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com