Amir Amir - 2 months ago 45
ASP.NET (C#) Question

resize image without losing quality MVC 4

I just want to re-size image without losing quality
can I use this ?

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
WebImage img = new WebImage(file.InputStream);
if (img.Width > 1000)
img.Resize(1000, 1000);
img.Save("path");
return View();
}


or WebImage resize but loss image quality ?
thanks

Answer

Here is a code I use. Call ResizeImage method in your action.

public class Size
{
    public Size(int width, int height)
    {
        Width = width;
        Height = height;
    }
    public int Width { get; set; }
    public int Height { get; set; }
}

public static bool ResizeImage(string orgFile, string resizedFile, ImageFormat format, int width, int height)
{
    try
    {
        using (Image img = Image.FromFile(orgFile))
        {
            Image thumbNail = new Bitmap(width, height, img.PixelFormat);
            Graphics g = Graphics.FromImage(thumbNail);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            Rectangle rect = new Rectangle(0, 0, width, height);
            g.DrawImage(img, rect);
            thumbNail.Save(resizedFile, format);
        }

        return true;
    }
    catch (Exception)
    {
        return false;
    }
}