C# - convert any filetype to bitmap show in picturebox

575 views Asked by At

I want a OpenFileDialog to select any file-types and show the file bits in a bitmap image. I mean the selected file contain some 0/1 bits, I want to show them in black and white image. Any Idea?

1

There are 1 answers

10
Olivier Jacot-Descombes On

If the file is a valid image file, you can simply read an image like this:

Image image = Image.FromFile(pathOfImage);

...and then assign it to a picture box.

You will need a reference to System.Drawing.dll and include a using using System.Drawing; at the top of your code.


If the bits in the file, however, represent the black and white pixels, you will need to draw the image yourself.

First create a Bitmap, then create a graphics object from it. You can then draw the pixels on it.

using (var image = new Bitmap(width, height))
using (var g = Graphics.FromImage(image)) {
    // TODO: Draw using the graphics object. (Insert code below)
}

You can use the answer from this answer to read the bits: BinaryReader - Reading a Single “ BIT ”?

In a double loop you can then iterate through the bits. Assuming that the bits are stored line by line:

using (var stream = new FileStream("file.dat", FileMode.Open)) {
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            bool? bit = stream.ReadBit(true);
            if (bit == null) { // No more bits
                return; 
            }
            if (bit.Value) {
                g.FillRectangle(Brushes.White, x, y, 1, 1);
            }
        }
    }
}

Finally assign the image to the picture box

pictureBox1.Image = image;