Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
To change brightness of an image in c#.net 4 i have used the following method.


C#
public void SetBrightness(int brightness)
       {
           imageHandler.RestorePrevious();
           if (brightness < -255) brightness = -255;
           if (brightness > 255) brightness = 255;
           ColorMatrix cMatrix = new ColorMatrix(CurrentColorMatrix.Array);
           cMatrix.Matrix40 = cMatrix.Matrix41 = cMatrix.Matrix42 = brightness / 255.0F;
           imageHandler.ProcessBitmap(cMatrix);
       }

         internal void ProcessBitmap(ColorMatrix colorMatrix)
             {
               Bitmap bmap = new Bitmap(_currentBitmap.Width, _currentBitmap.Height)

               ImageAttributes imgAttributes = new ImageAttributes();
               imgAttributes.SetColorMatrix(colorMatrix);
               Graphics g = Graphics.FromImage(bmap);
               g.InterpolationMode = InterpolationMode.NearestNeighbor;
               g.DrawImage(_currentBitmap, new Rectangle(0, 0, _currentBitmap.Width,
               _currentBitmap.Height), 0, 0, _currentBitmap.Width,
               _currentBitmap.Height,  GraphicsUnit.Pixel, imgAttributes);
               _currentBitmap = (Bitmap)bmap.Clone();


           }


If brightness is changed several times then "Out of memory" exception is shown. I have tried to use "Using block" but went in vein.

Any ideas?

please see the link
Image Processing Using Matrices in C#
and suggest if any types of optimization is possible in the methods (Rotation, brightness, crop and undo).
Posted
Updated 10-Apr-12 20:46pm
v2

1 solution

Try disposing of old bitmaps: each time you call ProcessBitmap you build two more (one with the new Bitmap at teh beginning, and another with the bmap.Clone at the end).
Use Dispose on _currentBitmap before you assign the new value, and don't do the Clone at all since it really doesn't do anything useful - it just takes time and memory.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900