Paste the contents of a Bitmap into a PictureBox
Asked Answered
T

1

0

I'm currently writing a little paint application where the user is able to draw on a Panel. I am working on the select tool and want to be able to select a certain area of the Panel, and then paste this selected area directly into a PictureBox that I have just to the right of the Panel.

My problem is that my code at the moment is not working correctly, when I try to paste the Bitmap that I am creating from the panel I am getting a big red X in the PictureBox instead of the actual image. I know that the image is copying to the Bitmap correctly because I tried putting some code around it to save it to disk as a jpeg and then look at the image, and it is all displaying fine.

Here is my code:

private void tbCopy_Click(object sender, EventArgs e)
{
    int width = selectList[0].getEnd().X - selectList[0].getInitial().X;
    int height = selectList[0].getEnd().Y - selectList[0].getInitial().Y;

    using (Bitmap bmp = new Bitmap(width, height))
    {
        pnlDraw.DrawToBitmap(bmp, new System.Drawing.Rectangle(
                                      selectList[0].getInitial().X,
                                      selectList[0].getInitial().Y, 
                                      width, height));
        pbPasteBox.Image = bmp;             
    }
}   

the width and height are just the dimensions of the area that I want to copy, and selectList is a List that contains one object which contains the coordinates of the area I want to copy.

Any help would be greatly appreciated.

Thomas answered 16/4, 2013 at 6:34 Comment(3)
first thought would be your bitmap is being garbage collected, edit, what happens if you take out your using bracket?Occurrence
removing the using fixes it haha! thanks for the help Sayse!Thomas
No worries ;) I'll write a bit more of an explanation :POccurrence
O
6

Your problem is the using(){} when the code inside the using braces has completed the object inside the () is disposed of as it is deemed no longer needed.

Simply removing the brace to just have Bitmap bmp = new Bitmap(width, height) should solve your problem

Occurrence answered 16/4, 2013 at 6:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.