This example shows how to draw an image from a file, put a frame round it and then draw some rotated text at the bottom right of the image.
Drawing the Image

We create a Bitmap from the core file we are interested in. Because we want the aspect ratio to be maintained we calculate what it is, and then scale the image size down by that factor. Note that we can apply a scalar multiple directly to the Size structure, and then add it to another Size.


using (Image image = Bitmap.FromFile(Server.MapPath("rez/ryk-naves-4Q6kXLAKK_Y-unsplash.jpg"))) {
  double scale = 640.0 / image.Width;
  Size size = (image.Size * scale) + new Size(8, 8);

Drawing a Frame

We then create a new Bitmap that size and draw our source image into it. We include a filled black rectangle in the background so we get a black border around the image. You can use draw operations for rectangles but a fill is guaranteed to be inside the rectangle.


  using (Bitmap bm = new Bitmap(size)) {
    using (Graphics graphics = Graphics.FromImage(bm)) {
      graphics.FillRectangle(Brushes.Black, 2, 2, bm.Width - 4, bm.Height - 4);
      graphics.DrawImage(image, 4, 4, bm.Width - 8, bm.Height - 8);

Drawing the Text

We want to draw a caption vertically up the side of the output image. So we need to use MeasureString to find out how much space it is going to take up. Once we have established that then we can enlarge the bitmap that much on the right hand side.

To draw the text vertically we need to apply a rotation transform followed by a translation to move it into the correct position.


      Font font = new Font("Arial", 14, FontStyle.Regular);
      string caption = "Great White Egret © Ryk Naves 2018";
      Size sz = (Size)graphics.MeasureString(caption, font);
      bm.Resize(bm.Width + sz.Height + 2, bm.Height);
      graphics.TranslateTransform(size.Width + 2, bm.Height - 6, MatrixOrder.Append);
      graphics.DrawString(caption, font, new SolidBrush(Color.Gray), 0, 0);


Finally we save the picture as a high quality JPEG image.


    EncoderParameters pars = new EncoderParameters() { Quality = 75 };
    bm.Save(Server.MapPath("Drawing_an_Image_1.jpg"), ImageFormat.Jpeg, pars);

Input and Output

Sample input and output images are shown below.