C# Scale bitmap

The following code scales a bitmap from the filesystem to a defined width:

        private static void ResizeBitmap(string filename) {
            using (Bitmap source = new Bitmap(filename))
            {
                const int width = 1024;
                int height = (int) (((double)width/source.Width)*source.Height);

                using (Bitmap result = new Bitmap(width, height))
                {
                    using (Graphics g = Graphics.FromImage(result))
                    {
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.DrawImage(source, 0, 0, width, height);
                    }

                    // if you do not execute that line it will lead to an Generic GDI+ exception
                    source.Dispose();

                    result.Save(filename, ImageFormat.Png);
                }
            }
        }

Leave a comment

Your email address will not be published. Required fields are marked *