4

I need to stretch various sized bitmaps to fill a PictureBox. PictureBoxSizeMode.StretchImage sort of does what I need but can't think of a way to properly add text or lines to the image using this method. The image below is a 5x5 pixel Bitmap stretched to a 380x150 PictureBox.

using pictureBox.SizeMode = PictureBoxSizeMode.StretchImage

pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox.Image = bmp;

I tried adapting this example and this example this way

using (var bmp2 = new Bitmap(pictureBox.Width, pictureBox.Height))
using (var g = Graphics.FromImage(bmp2))
{
    g.InterpolationMode = InterpolationMode.NearestNeighbor;
    g.DrawImage(bmp, new Rectangle(Point.Empty, bmp2.Size));
    pictureBox.Image = bmp2;
}

but get this

using g.DrawImage(bmp, new Rectangle(Point.Empty, bmp2.Size))

What am I missing?

Community
  • 1
  • 1
jacknad
  • 13,483
  • 40
  • 124
  • 194

2 Answers2

5

It appears you're throwing away the bitmap (bmp2) you'd like to see in your picture box! The using block from the example you posted is used because the code no longer needs the Bitmap object after the code returns. In your example you need the Bitmap to hang around, hence no using-block on the bmp2 variable.

The following should work:

using (bmp)
{
    var bmp2 = new Bitmap(pictureBox.Width, pictureBox.Height);
    using (var g = Graphics.FromImage(bmp2))
    {
        g.InterpolationMode = InterpolationMode.NearestNeighbor;
        g.DrawImage(bmp, new Rectangle(Point.Empty, bmp2.Size));
        pictureBox.Image = bmp2;
    }
}
Community
  • 1
  • 1
user7116
  • 63,008
  • 17
  • 141
  • 172
3

The red X on white background happens when you have an exception in a paint method.

Your error is that you are trying to assign a disposed bitmap as the image source of your picturebox. The use of "using" keyword will dispose the bitmap you are using in the picturebox!

So your exception, i know, will be ObjectDisposedException :)

You should create the bitmap once and keep it until it is not needed anymore.

void ReplaceResizedPictureBoxImage(Bitmap bmp)
{
    var oldBitmap = pictureBox.Image;

    var bmp2 = new Bitmap(pictureBox.Width, pictureBox.Height);
    using (var g = Graphics.FromImage(bmp2))
    {
        g.InterpolationMode = InterpolationMode.NearestNeighbor;
        g.DrawImage(bmp, new Rectangle(Point.Empty, bmp2.Size));
        pictureBox.Image = bmp2;
    }

    if (oldBitmap != null)
        oldBitmap.Dispose();
}

This function will allow you to replace the old bitmap disposing the previous one, if you need to do that to release resources.

Salvatore Previti
  • 8,956
  • 31
  • 37