ASP.NET - Resize Images Without Loss Of Quality

Sometimes we need to re size the images uploaded by the users to show in image Gallery. There are many ways to do this. Following is one of the code snippet to re size the image without losing the original quality of the image.It directly re sizes the image stream and returns the byte array to save in the database

public static byte[] ResizeImage(Stream oStream, int width, int height)
    {
        Bitmap MainImage = new Bitmap(oStream);
        int newWidth = MainImage.Width;
        int newHeight = MainImage.Height;
        double aspectRatio = (double)MainImage.Width / (double)MainImage.Height;
        if (aspectRatio <= 1 && MainImage.Width > width)
        {
            newWidth = width;
            newHeight = (int)Math.Round(newWidth / aspectRatio);
        }
        else if (aspectRatio > 1 && MainImage.Height > height)
        {
            newHeight = height;
            newWidth = (int)Math.Round(newHeight * aspectRatio);
        }
        Bitmap ResizedImage = new Bitmap(MainImage, newWidth, newHeight);
        Graphics g = Graphics.FromImage(ResizedImage);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
        g.DrawImage(MainImage, 0, 0, ResizedImage.Width, ResizedImage.Height);
        MainImage.Dispose();

        MemoryStream MStream = new MemoryStream();
        ResizedImage.Save(MStream, System.Drawing.Imaging.ImageFormat.Bmp);
        MainImage.Dispose();
        return MStream.ToArray();
    }

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment