Search code examples
c#imagegraphicsdrawingbitmap

C# Graphics class: get size of drawn content


I am writing to a Graphics object dynamically and don't know the actual size of the final image until all output is passed.

So, I create a large image and create Graphics object from it:

int iWidth = 600;
int iHeight = 2000;

bmpImage = new Bitmap(iWidth, iHeight);            
graphics = Graphics.FromImage(bmpImage);
graphics.Clear(Color.White);        

How can I find the actual size of written content, so I will be able to create a new bitmap with this size and copy the content to it.

It is really hard to calculate the content size before drawing it and want to know if there is any other solution.


Solution

  • The best solution is probably to keep track of the maximum X and Y values that get used as you draw, though this will be an entirely manual process.

    Another option would be to scan full rows and columns of the bitmap (starting from the right and the bottom) until you encounter a non-white pixel, but this will be a very inefficient process.

    int width = 0;
    int height = 0;
    
    for(int x = bmpImage.Width - 1, x >= 0, x++)
    {
        bool foundNonWhite = false;
    
        width = x + 1;
    
        for(int y = 0; y < bmpImage.Height; y++)
        {
            if(bmpImage.GetPixel(x, y) != Color.White)
            {
                foundNonWhite = true;
                break;
            }
        }
    
        if(foundNonWhite) break;
    }
    
    for(int y = bmpImage.Height - 1, x >= 0, x++)
    {
        bool foundNonWhite = false;
    
        height = y + 1;
    
        for(int x = 0; x < bmpImage.Width; x++)
        {
            if(bmpImage.GetPixel(x, y) != Color.White)
            {
                foundNonWhite = true;
                break;
            }
        }
    
        if(foundNonWhite) break;
    }
    

    Again, I don't recommend this as a solution, but it will do what you want without your having to keep track of the coordinate space that you actually use.