- Course
- Binary Files
- Encrypt a BMP image
Encrypt a BMP image
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a program in C# to encrypt an image in Windows bitmap format. First you should check that it is a valid .bmp image, checking the header data 'BM'. If it is a valid .bmp image then encrypt the image by inverting the first two bytes containing the mark 'BM' by 'MP'.
You can use the advanced FileStream
constructor to read and write at the same time.
It is a format of the Windows operating system. You can save images up to 24 bits (16.7 million colors).
The header of a BMP image is as follows:
Description | Bytes |
Type (BM) | 0-1 |
Size | 2-5 |
Reserved | 6-9 |
Start of image data | 10-13 |
Bitmap size | 14-17 |
Width (pixels) | 18-21 |
High (pixels) | 22-25 |
Number of plans | 26-27 |
Size of each point | 28-29 |
Compression | 30-33 |
Image size | 34-37 |
Horizontal resolution | 38-41 |
Vertical resolution | 42-45 |
Table color size | 46-49 |
Color counter | 50-53 |
Input
Output
Solution
using System.IO;
public class EncryptBMPImage
{
public static void Main(string[] args)
{
string fileName = "logo.bmp";
using (FileStream file = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite))
{
char b1 = (char) file.ReadByte();
char b2 = (char) file.ReadByte();
if (b1 != 'B' || b2 != 'M')
{
return; // Not a BMP file
}
else
{
file.Seek(0, SeekOrigin.Begin);
file.WriteByte((byte)'M');
file.WriteByte((byte)'B');
}
}
}
}