Here's a C# code that generates a BMP file with a circle:
using System;
using System.IO;
public class BmpGenerator
{
public static void Main()
{
int width = 500;
int height = 500;
int radius = 200;
int centerX = width / 2;
int centerY = height / 2;
// Create a byte array for the pixel data (24-bit BMP)
byte[] pixelData = new byte[width * height * 3];
// Fill the background with white (R=255, G=255, B=255)
for (int i = 0; i < pixelData.Length; i += 3)
{
pixelData[i] = 255; // Blue
pixelData[i + 1] = 255; // Green
pixelData[i + 2] = 255; // Red
}
// Draw a black circle
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// Check if the pixel is inside the circle
double distance = Math.Sqrt(Math.Pow(x - centerX, 2) + Math.Pow(y - centerY, 2));
if (distance <= radius)
{
int index = (y * width + x) * 3;
pixelData[index] = 0; // Blue
pixelData[index + 1] = 0; // Green
pixelData[index + 2] = 0; // Red
}
}
}
// Calculate the row size in bytes (must be a multiple of 4)
int rowSize = width * 3;
int padding = (4 - (rowSize % 4)) % 4;
int newRowSize = rowSize + padding;
int imageSize = newRowSize * height;
// Create a new byte array with padding and reversed rows
byte[] paddedPixelData = new byte[imageSize];
for (int y = 0; y < height; y++)
{
int sourceRow = y;
int destRow = height - 1 - y; // Reverse the row order
int startIndex = sourceRow * width * 3;
int paddedStartIndex = destRow * newRowSize;
Array.Copy(pixelData, startIndex, paddedPixelData, paddedStartIndex, rowSize);
// Add padding bytes (if any)
for (int p = 0; p < padding; p++)
{
paddedPixelData[paddedStartIndex + rowSize + p] = 0;
}
}
// Calculate the file size
int fileSize = 54 + imageSize; // 54 bytes for headers
// Create the BMP file
using (BinaryWriter writer = new BinaryWriter(File.Open("output.bmp", FileMode.Create)))
{
// File Header
writer.Write((byte)'B');
writer.Write((byte)'M');
writer.Write(fileSize);
writer.Write((int)0); // Reserved
writer.Write(54); // Offset to pixel data
// DIB Header (BITMAPINFOHEADER)
writer.Write(40); // Header size
writer.Write(width); // Image width
writer.Write(height); // Image height
writer.Write((short)1); // Color planes
writer.Write((short)24); // Bits per pixel
writer.Write(0); // Compression method (none)
writer.Write(imageSize); // Image size
writer.Write(2835); // Horizontal resolution (pixels per meter, 72 DPI)
writer.Write(2835); // Vertical resolution (pixels per meter, 72 DPI)
writer.Write(0); // Colors in palette
writer.Write(0); // Important colors
// Pixel Data
writer.Write(paddedPixelData);
}
}
}
This code creates a 500x500 pixel BMP image with a black circle centered in a white background. The BMP file is saved as "output.bmp". The code manually constructs the BMP file structure, including headers and pixel data, ensuring correct formatting and padding.