0

I have an image of a and b width and height.

I need to create a new image of x and y height, keeping the original contents of the image central and adding white pixels to fill the part of the image that has been added to make it x and y width.

So almost like a white border all the way around

This is as close as I get at the moment. But i can't get my head around how to get the calculated border size and apply it.

// download the file from the url as a stream
    using System.Net.WebClient webClient = new System.Net.WebClient();
    using Stream stream = webClient.OpenRead(urlToImage);

// create a bitmap image from the stream
    Bitmap bitmap = new Bitmap(stream);

// work out how much the image needs to get bigger by
    int increaseWidthBy = finalWidth - bitmap.Width;
    int increaseHeightBy = finalHeight - bitmap.Height;
        
    Graphics gr = Graphics.FromImage(bitmap);
    gr.DrawLine(new Pen(Brushes.White, 20), new Point(0, 0), new Point(0, 40));
    gr.DrawLine(new Pen(Brushes.White, 20), new Point(0, 0), new Point(40, 0));
    gr.DrawLine(new Pen(Brushes.White, 20), new Point(0, 40), new Point(40, 40));
    gr.DrawLine(new Pen(Brushes.White, 20), new Point(40, 0), new Point(40, 40));

    gr.DrawImage(bitmap, 0, 0, finalWidth, finalHeight);

    Bitmap newimage = new Bitmap(finalWidth, finalHeight);
    using MemoryStream memory = new MemoryStream();
    using FileStream fs = new FileStream(fileName, FileMode.Create);
    newimage.Save(memory, ImageFormat.Jpeg);
    byte[] bytes = memory.ToArray();
    fs.Write(bytes, 0, bytes.Length);

Any help would be greatly appreciated.

Trevor Daniel
  • 3,785
  • 12
  • 53
  • 89
  • Does this answer your question? [How to resize an Image C#](https://stackoverflow.com/questions/1922040/how-to-resize-an-image-c-sharp) – Umutambyi Gad Jun 30 '20 at 12:02

1 Answers1

0

So. I cheated. I used a library... "ImageProcessor"

This is what worked for me:

public static void ResizeImage2(string urlToImage, int finalWidth, int finalHeight, string fileName)
    {
        // download the file from the url as a stream
        using WebClient webClient = new WebClient();
        using Stream stream = webClient.OpenRead(urlToImage);

        // convert the stream to an Image
        System.Drawing.Image newImage = Bitmap.FromStream(stream);

        ImageProcessor.ImageFactory imageFactory = new ImageProcessor.ImageFactory();
        ISupportedImageFormat format = new JpegFormat { Quality = 70, IsIndexed = false };
        
        ResizeLayer layer = new ResizeLayer(new Size(finalWidth, finalHeight), ResizeMode.BoxPad, AnchorPosition.Center, true);

        imageFactory.Load(newImage)
            .Resize(layer)
            .BackgroundColor(Color.White)
            .Format(format)
            .Save(fileName);
    }
Trevor Daniel
  • 3,785
  • 12
  • 53
  • 89