How to load a bitmap file in a .NET console application
Asked Answered
K

2

6

I'm trying to make a Console Application with C# that starts by loading an 8-bit gray level bitmap file (typically BMP) and transform it into a two dimensional byte array, where (as you would expect) the byte at position x,y is the intensity of pixel x,y. I then have a lot of code that will do some work on the bitmap as array.

The trouble is that I've seen this done with calls from WPF modules which just are not available in a console application. I don't want to use System.Windows.Media.Imaging for example.

Does anyone have any suggestion as to how I can do this without too much trouble?

Kutuzov answered 18/2, 2014 at 19:42 Comment(1)
Use System.Drawing.BitmapAnnular
F
13

You can add the System.Drawing.dll assembly to your project's references. Then you can use the System.Drawing.Bitmap class.

Add the following to the top of your code file to add the namespace System.Drawing:

using System.Drawing;

To load a bitmap:

Bitmap bitmap = (Bitmap)Image.FromFile(@"mypath.bmp");

When you're done with the bitmap:

bitmap.Dispose();

You can get the width, the height, and any pixels within the bitmap:

int width = bitmap.Width;
int height = bitmap.Height;
Color pixel00 = bitmap.GetPixel(0, 0);
Footpound answered 18/2, 2014 at 19:46 Comment(3)
+1. And use Bitmap.LockBits if you want to play with underlying raw data.Carrew
@AlexeiLevenkov Correct, but a bit too advanced for this OP I think. That's only an optimization.Footpound
Maybe, but feels like exactly what OP wants to do - "...transform it into a two dimensional byte array...".Carrew
W
0

Use the System.Drawing.Bitmap ctor that takes a path to the image file.

Whisper answered 18/2, 2014 at 19:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.