Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IFormFile to Image in Asp Core

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 ?

like image 481
mr-dortaj Avatar asked May 16 '19 04:05

mr-dortaj


1 Answers

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);
                }
            }
        }
like image 156
VahidN Avatar answered Nov 15 '22 16:11

VahidN