Search code examples
c#winformspicturebox

How can I add changes to an pictureBox image without using the Action Paint?


I have various reasons I cannot use the Action Paint in my PictureBox one major is I am parenting multiple pictureboxes to the main PictureBox, I am trying to figure out how using the below code to write to the image once I have placed multiple rectangles across it. I then write out the file.

        private void Finished()
        {
            if(pictureBox.Image != null)
            {
                for(int i = 1; i < samples.Count; i++) 
                { 
                    //provide new scale against zoom feature
                    var zoom = 1f;
                    RectangleF area = Rectangle.Empty;
                    SetImageScale(pictureBox, out area, out zoom);
                    Point location = Point.Round(new PointF((samples[i].Rect.X - area.X) / zoom, (samples[i].Rect.Y - area.Y) / zoom));
                    Size size = Size.Round(new SizeF(samples[i].Rect.Width / zoom, samples[i].Rect.Height / zoom));
                    var resizedRect = new Rectangle(location, size);
                    //end provider

                    //testing if the image saves correctly
                    var hWnd = pictureBox.Handle; //this handle only writes to the window not image
                    Graphics e = Graphics.FromHwnd(hWnd);
                    using (Brush brush = new SolidBrush(Color.White))
                    {
                        var image = pictureBox.Image;
                        e.FillRectangle(brush, resizedRect);
                    }
                }
                //save the image
                pictureBox.Image.Save($"{ConfigSettings.EditedSamplesDirectory}\\{Path.GetFileName(currentImagePath)}");
                //remove image from paths
                imagePaths.Remove(currentImagePath);
                form1.Refresh();
                LoadNextImage();
            }
        }

I tried in on paint with a boolean expected to write to the main image but it did not work there are other various methods I have tried by looking at google and this search nothing came up on how not to do this by OnPaint Action using e.Graphics.


Solution

  • the final code fix was to change these lines..

                //testing if the image saves correctly
                var hWnd = pictureBox.Handle; //this handle only writes to the window not image
                Graphics e = Graphics.FromHwnd(hWnd);
    

    //FIX

                //testing if the image saves correctly
                Graphics e = Graphics.FromImage(pictureBox.Image);
    

    Thank you jmcilhinney really appreciate it.