user3226824
user3226824

Reputation: 47

How To Read File Into A Two Dimensional Array in c#

I have a file (c:\kk.bmp). I want to read this file into a two dimensional array[Width,Height] of byte and a two dimensional array[Width,Height] of Int32, such as

byte[,] byte_array = File.ReadAllBytes(filename_mpeg4); // Not correct

I want to read the file "filename_mpeg4" into two dimensions in an array of byte and array of Int32 in C#.

Upvotes: 0

Views: 1198

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112279

BMSs and MPEG4s are quite different things. A Bitmap has two dimensions. Mpeg4 or other video files store a list of two dimensional frames using complex compression algorithms. Therefore you have two space plus one time dimension. Your array would have to be three dimensional. It is not clear from your question whether you are trying to read an image (c:\kk.bmp) or a video (filename_mpeg4).

In both cases you need to decode the file. Don't try to do that yourself, it's very complicated (especially for videos).

Reading a bitmap is easy:

Bitmap myBitmap = new Bitmap(@"C:\kk.bmp");

This works for JPG, GIF, TIF and PNG as well. The decoders are integrated in the Windows OS.

You can draw on the image and do other things without converting it to some array.

// Example: Drawing a line on a bitmap
using (Graphics g = Graphics.FromImage( myBitmap )) {  
    g.DrawLine(Pens.Red, new Point(0, 0), new Point(100, 50));
}  

If you still need to extract the pixel data into an array, this SO answer might help you: C# Getting the pixel data efficiently from System.Drawing.Bitmap


Videos are a completely different story. There is no easy answer to your question. This CodeProject might help you: http://www.codeproject.com/Articles/9676/Extracting-still-pictures-from-movie-files-with-C.

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You can't do this with the current filestructure: you need to specify the length of at least one dimension. Something like:

int height = File.Read();
byte[] mp4 = File.ReadAllBytes(filename_mpeg4);
int width = mp4.length/height;
byte[,] byte_array = new byte[height,mp4.length/height];
int k = 0;
for(int i = 0; i < height; i++) {
    for(int j = 0; j < width; j++) {
        byte_array[i,j] = mp4[k++];
    }
}

Upvotes: 0

Related Questions