gdi+resolutionimage-resizingasp.net-3.5

Reduce image size, but keep maximum quality/resolution?


I'm resizing an image using bitmap.GetThumbnailImage() however I seem to be losing image quality/resolution. For example the original image was 300dpi resolution, and the resized 1 is much smaller.

How can I retain the image resolution when resizing?


Solution

  • Here's a function I use to reduce my images. The quality is excellent.

        private static Image ResizeImage(Image imgToResize, Size size)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;
    
            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;
    
            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);
    
            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;
    
            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);
    
            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    
            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();
    
            return (Image)b;
        }
    

    Here's how I use it:

            int length = (int)stream.Length;
            byte[] tempImage = new byte[length];
            stream.Read(tempImage, 0, length);
    
            var image = new Bitmap(stream);
            var resizedImage = ResizeImage(image, new Size(300, 300));
    

    Holler if you need help getting it running.