Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently scale and crop images in an ASP.NET app?

Tags:

asp.net

image

We're having problems with an ASP.NET application which allows users to upload, and crop images. The images are all scaled to fixed sizes afterwards. We basically run out of memory when a large file is processed; it seems that the handling of JPEG is rather inefficient -- we're using System.Drawing.BitMap. Do you have any general advice, and perhaps some pointers to a more efficient image handling library? What experiences do you have?

like image 974
Daniel Schierbeck Avatar asked Jan 24 '23 18:01

Daniel Schierbeck


1 Answers

I had the same problem, the solution was to use System.Drawing.Graphics to do the transformations and dispose every bitmap object as soon as I was finished with it. Here's a sample from my library (resizing) :

    public Bitmap ApplyTo(Bitmap bitmap)
    {
        using (bitmap)
        {
            Bitmap newBitmap = new Bitmap(bitmap, CalculateNewSize(bitmap));

            using (Graphics graphics = Graphics.FromImage(newBitmap))
            {
                graphics.SmoothingMode =
                    SmoothingMode.None;
                graphics.InterpolationMode =
                    InterpolationMode.HighQualityBicubic;
                graphics.CompositingQuality =
                    CompositingQuality.HighQuality;

                graphics.DrawImage(
                    bitmap,
                    new Rectangle(0, 0, newBitmap.Width, newBitmap.Height));
            }

            return newBitmap;
        }
    }
like image 91
Diadistis Avatar answered Mar 08 '23 23:03

Diadistis