0

I'm trying to crop and resize an image in PictureBox1. My code:

//original image for eventually undo
undoImage = pictureBox1.BackgroundImage.Clone() as Image;
Bitmap sourceBitmap = new Bitmap(pictureBox1.BackgroundImage, pictureBox1.Width, pictureBox1.Height);
Graphics g = pictureBox2.CreateGraphics();
g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width, pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
sourceBitmap.Dispose();

And it working properly on two PictureBoxes. But PictureBox2.Image,PictureBox2.BackgroundImage (and any other including ErrorImage...) = null. I tried PictureBox.DrawToBitmap, and other, like g.GetHdc() found on google, but unsuccessful.

My question:
How do I properly copy the edited image from PictureBox2 to PictureBox1?

mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
Daniel K
  • 1
  • 1
  • 1
    You have to assign `PictureBox.Image` to be able to use it. Drawing using graphics doesn't generate an `Image` for you, so (I guess) it stays `null`. See [this answer](https://stackoverflow.com/a/24620810/1997232). – Sinatr Sep 14 '17 at 12:15
  • `undoImage = pictureBox1.BackgroundImage.Clone() as Image;` this is wrong. its (as Sinatr says) `.Image` not `.BackGroundImage` – EpicKip Sep 14 '17 at 12:19
  • `CreateGraphics` is volatile. It's lifespan is limited to the scope in which it is used. You need to be drawing in the appropriate `Paint` method(s). And @Sinatr is correct...why wouldn't it be null? You never assigned an `Image` object, you just drew on it through brute force. – DonBoitnott Sep 14 '17 at 12:23
  • `BackgroundImage` is type `Image`. This is not a problem – Daniel K Sep 14 '17 at 12:26
  • Do not Dispose() it *before* you are going to display it. Dispose the old one you no longer need. probably stored in PictureBox2.Image – Hans Passant Sep 14 '17 at 12:30

1 Answers1

-2

Trivial solution:

undoImage = pictureBox1.BackgroundImage.Clone() as Image;
Bitmap sourceBitmap = new Bitmap(pictureBox1.BackgroundImage, pictureBox1.Width, pictureBox1.Height);
using (Graphics g = Graphics.FromImage(sourceBitmap))
{
      g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox2.Width,pictureBox2.Height), rectCropArea, GraphicsUnit.Pixel);
}
pictureBox1.BackgroundImage = sourceBitmap;
Sinatr
  • 20,892
  • 15
  • 90
  • 319
Daniel K
  • 1
  • 1