Search code examples
c#imagedrawingfill

Fill / append rectangle on bottom of image c#


I need to fill an rectangle on bottom of my image, but not over the image, so it should be a kind of append a rectangle to bottom of image.

What I have for now:

    private void DrawRectangle()
    {
        string imageFilePath = @"c:\Test.jpg";
        Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);
        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            using (Image img = Image.FromFile(imageFilePath))
            {
                SolidBrush brush = new SolidBrush(Color.Black);
                int width = img.Width;
                int height = img.Height - 350;
                graphics.FillRectangle(brush, 0, height, width, 350);
            }
        }
        bitmap.Save(@"c:\Test1.jpg");
    }

But this is over the image.

Any idea's?

Thank you.


Solution

  • You need to know the dimensions of your original image in order to set the size of the new bitmap, which must be larger to accommodate the rectangle.

    private void DrawRectangle()
    {
        string imageFilePath = @"c:\Test.jpg";
        int rectHeight = 100;
    
        using (Image img = Image.FromFile(imageFilePath)) // load original image
        using (Bitmap bitmap = new Bitmap(img.Width, img.Height + rectHeight)) // create blank bitmap of desired size
        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            // draw existing image onto new blank bitmap
            graphics.DrawImage(img, 0, 0, img.Width, img.Height); 
            SolidBrush brush = new SolidBrush(Color.Black);
            // draw your rectangle below the original image
            graphics.FillRectangle(brush, 0, img.Height, img.Width, rectHeight); 
            bitmap.Save(@"c:\Test1.bmp");
        }
    }