Generate placeholder image in C#

Visual Studio

In C#, you can generate a simple placeholder image using the System.Drawing namespace. Here's an example of how you can create a 200x200 pixel placeholder image with a solid background color:

using System;
using System.Drawing;
using System.Drawing.Imaging;

class Program
{
    static void Main()
    {
        int width = 200;
        int height = 200;

        // Create a new bitmap with the specified width and height
        Bitmap bitmap = new Bitmap(width, height);

        // Create a graphics object from the bitmap
        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            // Fill the entire bitmap with a solid color (in this case, white)
            graphics.FillRectangle(Brushes.White, 0, 0, width, height);

            // Optionally, you can draw text or other shapes on the image here
            // For example:
            // graphics.DrawString("Placeholder", new Font("Arial", 12), Brushes.Black, new PointF(10, 10));
        }

        // Save the bitmap to a file (you can choose the format)
        bitmap.Save("placeholder.png", ImageFormat.Png);

        // Dispose of the bitmap object
        bitmap.Dispose();

        Console.WriteLine("Placeholder image generated and saved as placeholder.png");
    }
}

This code creates a 200x200 pixel image with a white background. If you want a different background color, you can replace Brushes.White with another Brush of your choice.

You can also customize the image further by drawing shapes, text, or adding other elements using the Graphics object before saving the image.

Make sure to add a reference to the System.Drawing assembly in your project. In Visual Studio, you can do this by right-clicking on your project in the Solution Explorer, selecting "Add" > "Reference...", and then checking the "System.Drawing" checkbox in the ".NET" tab.

Comments
Loading...
Sorry! No comment found:(

There is no comment to show for this.

Leave your comment
Tested Versions
  • .NET 4.6
  • Visual Studio 2022