i need to resize file upload if file is image .
i write the extention for resize that :
public static Image ResizeImage(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;
}
and this is Upload Action :
[HttpPost("UploadNewsPic"), DisableRequestSizeLimit]
public IActionResult UploadNewsPic(IFormFile file)
{
if (file.IsImage())
{
}
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))
{
file.CopyTo(stream);
}
}
return Ok();
}
catch (Exception e)
{
return BadRequest();
}
}
now my problem is here => my extention just work on type of Image
file but type of this file is IFormFile
. how can i convert the IFormFile
to Image
type ?
You should use the Image.FromStream()
method to read the stream as an Image:
public async Task<IActionResult> FileUpload(IFormFile file)
{
if (file == null || file.Length == 0)
{
return BadRequest();
}
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
using (var img = Image.FromStream(memoryStream))
{
// TODO: ResizeImage(img, 100, 100);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With