Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize Image When Upload in Asp Core

I need to change the size of the photo and save it to a new size when the user selects a photo for the upload, before saving the photo.

i using this code but it not save with new size . whats the problem ?

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();
        }
    }

and this is Resize Extention :

 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;
    }
like image 696
mr-dortaj Avatar asked Oct 24 '25 08:10

mr-dortaj


2 Answers

You need to save the result from ResizeImage to the stream. Right now you are just copying the original file.

var img = await file.ResizeImage(3, 3);
img.Save(stream, SomeFormat);
like image 91
Magnus Avatar answered Oct 26 '25 22:10

Magnus


Your ResizeImage() function return a resized image, it doesn't edit the image itself, so you must set it to a variable.

if (file.IsImage())
{
    Image imageResized = await file.ResizeImage(3, 3);
    // ...
}
like image 32
ALFA Avatar answered Oct 26 '25 21:10

ALFA