techno
techno

Reputation: 6500

Parameter is not valid when creating Bitmap of size 6000X4500 Pixels

This simple line of code to create a large resolution Bitmap produces a parameter is not valid error

        Bitmap bitmap = new Bitmap(6500, 4500);

There are some questions on SO that refers to memory bottleneck with GDI+ Ref C# "Parameter is not valid." creating new bitmap

I depend upon GDI+ to do image processing.Changing all the code is not practical.Some users report issues when processing large resolution images.How can i get over this issue? My machine has 4GB of Ram and i have tried building x64 version of the exe as well.

Upvotes: 1

Views: 1035

Answers (1)

Silviu Berce
Silviu Berce

Reputation: 109

It's all about memory usage. I have done a small test, and here is the result. I create only a 500x500 Bitmap, but many times, without disposing it:

private void button1_Click(object sender, EventArgs e)
{
    int maxIterations = 5000;
    bool exceptionOccured = false;
    for (int i = 0; i < maxIterations; i++)
    {
        Bitmap bitmap = null;
        try
        {
            bitmap = new Bitmap(500, 500);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Exception after " + i.ToString() + " iterations" + Environment.NewLine + ex.Message);
            exceptionOccured = true;
            break;
        }
        finally
        {
            //dispose the bitmap when you don't need it anymore (comment/uncomment to see the different result)
            //bitmap?.Dispose();
        }
    }
    if (!exceptionOccured)
    {
        MessageBox.Show("No exception after " + maxIterations.ToString() + " iterations");
    }
}

And the result (the bitmap was not disposed): TEST result with exception

The same code, but disposing the bitmap in the finally block:

private void button1_Click(object sender, EventArgs e)
{
    int maxIterations = 5000;
    bool exceptionOccured = false;
    for (int i = 0; i < maxIterations; i++)
    {
        Bitmap bitmap = null;
        try
        {
            bitmap = new Bitmap(500, 500);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Exception after " + i.ToString() + " iterations" + Environment.NewLine + ex.Message);
            exceptionOccured = true;
            break;
        }
        finally
        {
            //dispose the bitmap when you don't need it anymore (comment/uncomment to see the different result)
            bitmap?.Dispose();
        }
    }
    if (!exceptionOccured)
    {
        MessageBox.Show("No exception after " + maxIterations.ToString() + " iterations");
    }
}

And the result (the bitmap was disposed): TEST result without exception

Upvotes: 3

Related Questions