6

How to convert Graphics into Image or Bitmap?

I have this code and it successfully crops my image in a picturebox but when I try to save it into a database.. it's empty.

Bitmap sourceBitmap = new Bitmap(pctImage.Image, pctImage.Width, pctImage.Height);
Graphics g = frmAdd.pctImage.CreateGraphics();

Rectangle rectCropArea;
rectCropArea = new Rectangle(50, 3, 230, 240);

g.DrawImage(sourceBitmap, new Rectangle(0, 0, frmAdd.pctImage.Width, frmAdd.pctImage.Height), rectCropArea, GraphicsUnit.Pixel);
sourceBitmap.Dispose();

What should I do with this one? Thanks.

CharlesB
  • 86,532
  • 28
  • 194
  • 218
James Andrew Cruz
  • 135
  • 1
  • 3
  • 9
  • You're not showing your code how you're trying to save it to a database. – BFree Oct 14 '12 at 12:52
  • 1
    Don't dispose the bitmap right after creating it. Save it first, *then* dispose it. That comes natural when you use the *using* statement. – Hans Passant Oct 14 '12 at 13:41

2 Answers2

3

like this:

  Bitmap bmp = new Bitmap(100,100,graphics);
Ravindra Bagale
  • 17,226
  • 9
  • 43
  • 70
0

Use a structure like this:

using (Bitmap bitmap = new Bitmap(rectangle.Width, rectangle.Height))
        {
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
               //draw image..
            }
            return bitmap;
        }
Caster Troy
  • 2,796
  • 2
  • 25
  • 45
  • 16
    Returning a disposed bitmap is a Really Bad Idea. – Hans Passant Oct 14 '12 at 13:42
  • 1
    Per Hans comment, the correct way to do this is to put *all* code using `bitmap` inside the `using .. bitmap`. So for the question asked, that means doing `save` where it now says `return bitmap`. (And *do not* return that bitmap, as it is disposed when the `using` context ends.) – ToolmakerSteve Sep 22 '17 at 19:32