Home > Software design >  Bitmap inside a bitmap
Bitmap inside a bitmap

Time:07-04

I am trying to insert an image 800x500 inside a blank bitmap of 850x610 in the center. The inner image should be in the center and It also has a title on the top. I am attaching an image to illustrate my idea:

Bordered Image inside another image/frame with a title

public static Bitmap AddBorder(Bitmap srcImage)
{
    Bitmap bmp = new Bitmap(srcImage.Width   45, srcImage.Height   100);
    Graphics g = Graphics.FromImage(bmp);
    g.DrawImage(srcImage, 0, 0);
    g.DrawImage(srcImage, new Rectangle(bmp.Width - 1, 0, 1, bmp.Height));
    g.DrawImage(srcImage, new Rectangle(0, bmp.Height - 1, bmp.Width, 1));
    return bmp;
}

I have tried to draw it using drawRectangle, drawImage etc. But, I cannot pad it properly as illustrated in the above image. I also cannot add the border to inner image. I want to get an idea about how to do that.

CodePudding user response:

The below sample sets the new bitmap size, it fills it with a background (black), draws the image in the center and finally after measuring the text will align it in the center (width check only).

public static Bitmap AddBorder(Bitmap srcImage, string text)
{
    Bitmap bmp = new Bitmap(850, 610);

    using(Graphics g = Graphics.FromImage(bmp))
    {
        // Background
        g.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

        // Source Image
        Rectangle rect = new Rectangle(25, 55, 800, 500);
        g.DrawImage(srcImage, rect);

        // Border
        int borderThickness = 2;
        using(Pen pen = new System.Drawing.Pen(Brushes.Black, borderThickness))
        {
            pen.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset;
            g.DrawRectangle(pen, new Rectangle(rect.X - borderThickness, rect.Y - borderThickness, rect.Width   borderThickness, rect.Height   borderThickness));
        }

        // Text String
        using (Font font = new Font("Arial", 16))
        {
            SizeF size = g.MeasureString(text, font);
            g.DrawString(text, font, Brushes.Black, new PointF((bmp.Width / 2) - (size.Width / 2), rect.Top - (size.Height   borderThickness)));
        }
    }

    return bmp;
}

Updated based on comments (Added also text above the centered image)!

  •  Tags:  
  • c#
  • Related