Search code examples
c#cachinggraphicsrotatetransform

Every time i rotate my images, my system memory keeps going up


Not sure if i'm being crazy, but i have a simple slider, that rotates the image, but every time i rotate the image, the system memory keeps going up, is there a way to clear this cache, i feel like i'm doing something wrong.

    public partial class Rulercompass : Form
    {

        Image img;
        int angle;

        public Rulercompass()
        {
            InitializeComponent();
        }

        private void Rulercompass_Load(object sender, EventArgs e)
        {

            img = Image.FromFile(@"C:\teste.jpg");

        }

        private void Rulercompass_Paint(object sender, PaintEventArgs e)
        {
            Bitmap bit_map = new Bitmap(img.Width, img.Height);
            using(Graphics gfx = Graphics.FromImage(bit_map))
        {
            gfx.TranslateTransform(bit_map.Width / 2, bit_map.Height / 2);
            gfx.RotateTransform(angle);
            gfx.TranslateTransform(-bit_map.Width / 2, -bit_map.Height / 2);
            gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;

            gfx.DrawImage(img, 0, 0);
            e.Graphics.TranslateTransform(this.Width / 2, this.Height / 2);
            e.Graphics.DrawImage(bit_map, -bit_map.Width/2,-bit_map.Height/2);
         }
        }

        private void Rulercompass_Resize(object sender, EventArgs e)
        {
            Invalidate();
        }

        private void trackBar1_ValueChanged(object sender, EventArgs e)
        {
            angle = trackBar1.Value;
            Invalidate();
        }
    }
}

Solution

  • Found solution, thanks to Ňɏssa Pøngjǣrdenlarp

    private void Rulercompass_Paint(object sender, PaintEventArgs e)
    {
        Bitmap bit_map = new Bitmap(img.Width, img.Height);
        using (Graphics gfx = Graphics.FromImage(bit_map))
        {
            gfx.TranslateTransform(bit_map.Width / 2, bit_map.Height / 2);
            gfx.RotateTransform(angle);
            gfx.TranslateTransform(-bit_map.Width / 2, -bit_map.Height / 2);
            gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
    
            gfx.DrawImage(img, 0, 0);
            e.Graphics.TranslateTransform(this.Width / 2, this.Height / 2);
            e.Graphics.DrawImage(bit_map, -bit_map.Width / 2, -bit_map.Height / 2);
        }
        bit_map.Dispose();// after using dispose this is what was missing
    }