Search code examples
c#interface

Image rotation and moving uses a lot of RAM


I'm developing an interface in C#. I move the indicators of my vehicle that I will control instantly. Some of these are rotation operations and some are move operations. These gestures consume a lot of RAM. I'm looking for a way to optimize. I am open to all your suggestions.

public static Bitmap RotateImage(Image image, float angle)
        {
            return RotateImage(image, new PointF((float)image.Width / 2, (float)image.Height / 2), angle);
        }
        public static Bitmap RotateImage(Image image, PointF offset, float angle)
        {
            if (image == null)
                throw new ArgumentNullException("image");

            Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
            rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            Graphics g = Graphics.FromImage(rotatedBmp);
            g.TranslateTransform(offset.X, offset.Y);
            g.RotateTransform(angle);
            g.TranslateTransform(-offset.X, -offset.Y);
            g.DrawImage(image, new PointF(0, 0));

            return rotatedBmp;
        }
        private void RotateImage(PictureBox pb, Image img, float angle)
        {
            if (img == null || pb.Image == null)
                return;

            Image oldImage = pb.Image;
            pb.Image = RotateImage(img, angle);
            if (oldImage != null)
            {
                oldImage.Dispose();
            }
        }
if (foot - first_value_roll == 1)
                    {
                        picture.Location = new Point(picture.Location.X, picture.Location.Y + 10);
                        first_value_roll = foot;
                    }
                    else if (foot - first_value_roll == -1)
                    {
                        picture.Location = new Point(picture.Location.X, picture.Location.Y - 10);
                        first_value_roll = foot;
                    }

C# Image rotation and moving uses a lot of RAM


Solution

  • The code you provided has a memory leak. You did not disposed the graphics object. So in your code:

       g.DrawImage(image, new PointF(0, 0));
       g.Dispose();  
       return rotatedBmp;
    

    I think this would resolve the problem.