C# Save Grayscale byte array Image (byte[]) as Bitmap file (.bmp) example

Here is a quick, dirty and inefficient example of how to save an 8bit Grey scale image stored in a C# byte array as a 32bit bitmap file (.bmp). Saving bitmaps can be quite suprisingly difficult in .NET so I am posting this for future reference!


This code copies each byte (8 bit pixel) in the 8bit image into an array of 32bit pixels (4 bytes per pixel) and then saves it to disk. Note that you have to build your project with the ‘Allow unsafe code’ checkbox checked (go to project properties / Build and you will see the ‘Allow unsafe code’ checkbox.)


public void SaveAsBitmap(string fileName, int width, int height, byte[] imageData)
// Need to copy our 8 bit greyscale image into a 32bit layout.
// Choosing 32bit rather than 24 bit as its easier to calculate stride etc.
// This will be slow enough and isn’t the most efficient method.
var data = new byte[width * height * 4];

int o = 0;

for (var i = 0; i < width * height; i++) { var value = imageData[i]; // Greyscale image so r, g, b, get the same // intensity value. data[o++] = value; data[o++] = value; data[o++] = value; data[o++] = 0; // Alpha isn't actually used } unsafe { fixed (byte* ptr = data) { // Craete a bitmap wit a raw pointer to the data using (Bitmap image = new Bitmap(width, height, width * 4, PixelFormat.Format32bppRgb, new IntPtr(ptr))) { // And save it. image.Save(Path.ChangeExtension(fileName, ".bmp")); } } } } [/crayon]


Thanks to all on this thread for the pointers!


Update, 02/2014:

This code will save the 8 bit bitmap in a compressed (but perfectly valid) format, to have your software save it in an uncompressed format take a look at this post.

Underwater Software!

Here is a nice video by the underwater videographer Tony Exall that demonstrates underwater photography using Cathx Ocean solid-state lights. The embedded software that runs on these lights was developed in ANSI C using the GNU Tool Chain (gcc et al.).


boost C++ read from serial port with timeout example

If you are doing any serial port communications these days in C++ and would like your code to be portable, then you are probably using boost’s asio::serial_port class.


One complication with using serial_port (and boost::asio more generally) is that it doesn’t provide a direct facility to allow synchronous blocking reads to time-out and return if no data arrives within a specified time period. Here is a little example that tries to read a character from COM3 (on windows..)


[crayon lang=”cpp”]

using namespace boost;

char read_char() {
asio::io_service io;
asio::serial_port port(io);“COM3”);

char c;

// Read 1 character into c, this will block
// forever if no character arrives.
asio::read(port, asio::buffer(&c,1));


return c;


In this example read() will block forever if no data arrives to the serial port, this is not always what you want, especially when dealing with possibly noisy or unreliable rs232 communication.


In order to take advantage of read time-outs you have to issue asynchronous reads and incorporate a deadline_timer which will cancel the read after a specified time, i.e. if the read hasn’t received the data it was expecting before the deadline_timer expires, then it will be cancelled.


Using asynchronous IO in boost is a bit involved and it can be quite quite messy, so I have written small class called blocking_reader which will block while trying to read a single character, and will time out if a character hasn’t been received in a specified number of milliseconds. It can be used like this:


[crayon lang=”cpp”]
#include “blocking_reader.h”

using namespace boost;

std::string read_response() {

asio::io_service io;
asio::serial_port port(io);“COM3”);

// A blocking reader for this port that
// will time out a read after 500 milliseconds.
blocking_reader reader(port, 500);

char c;

std::string rsp;

// read from the serial port until we get a
// \n or until a read times-out (500ms)
while (reader.read_char(c) && c != ‘\n’) {
rsp += c;

if (c != ‘\n’) {
// it must have timed out.
throw std::exception(“Read timed out!”);

return rsp;
The above code isn’t the most sensible or efficient but it shows the use of blocking_reader, which in this case times out reads after 500ms.


You open the serial_port as normal and then pass it to blocking_reader’s constructor along with a timeout value. You then use blocking_reader.read_char() to read a single character. If the read times out then read_char() will return false (otherwise it will return true!)


The code for blocking_reader can be downloaded from here, I have also included it below:


[crayon lang=”cpp”]
// blocking_reader.h – a class that provides basic support for
// blocking & time-outable single character reads from
// boost::asio::serial_port.
// use like this:
// blocking_reader reader(port, 500);
// char c;
// if (!reader.read_char(c))
// return false;
// Kevin Godden,


class blocking_reader
boost::asio::serial_port& port;
size_t timeout;
char c;
boost::asio::deadline_timer timer;
bool read_error;

// Called when an async read completes or has been cancelled
void read_complete(const boost::system::error_code& error,
size_t bytes_transferred) {

read_error = (error || bytes_transferred == 0);

// Read has finished, so cancel the
// timer.

// Called when the timer’s deadline expires.
void time_out(const boost::system::error_code& error) {

// Was the timeout was cancelled?
if (error) {
// yes

// no, we have timed out, so kill
// the read operation
// The read callback will be called
// with an error


// Constructs a blocking reader, pass in an open serial_port and
// a timeout in milliseconds.
blocking_reader(boost::asio::serial_port& port, size_t timeout) :
port(port), timeout(timeout),
read_error(true) {


// Reads a character or times out
// returns false if the read times out
bool read_char(char& val) {

val = c = ‘\0’;

// After a timeout & cancel it seems we need
// to do a reset for subsequent reads to work.

// Asynchronously read 1 character.
boost::asio::async_read(port, boost::asio::buffer(&c, 1),

// Setup a deadline time to implement our timeout.
this, boost::asio::placeholders::error));

// This will block until a character is read
// or until the it is cancelled.

if (!read_error)
val = c;

return !read_error;


.NET, WPF – BitmapImage File Locking

Q: How can I stop BitmapImage, in .NET Windows Presentation Foundation (WPF) from locking the source image file?


A: By default BitmapInfo seems to lock the source image file so that you can use the bitmapinfo object and modify or delete the source file at the same (or similar) time. For example, this C# will probably yield a locked image file:


var bitmap = new BitmapImage(new Uri(imageFilePath));
// use bitmap...


You can get around this locking problem as follows, it’s a little bit more long-winded but it worked for us….


var bitmap = new BitmapImage();
var stream = File.OpenRead(imageFilePath);
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
// Use bitmap.....


.NET WPF, Set Bitmap – Must create DependencySource on same Thread as the DependencyObject error

In WPF when you try to assign a bitmap to a property that’s bound to a UI element from a worker thread you may get the following error:


“Must create DependencySource on same Thread as the DependencyObject”


A simple way around this problem without having to jump through hoops and dispatch to the UI thread is to just freeze the bitmap before assigning it, like this:


var bitmap = new BitmapImage(new Uri(CurrentImageFilePath));
this.CurrentImage = bitmap;


I hope this helps someone who’s stuck with this annoying error!


Breakpoints Not Working / .NET C++/CLI

I was having some trouble getting Visual Studio 2010 to stop at breakpoints in some unmanaged C++ code that’s in a C++/CLI project that I am working on, and as we all know Software Developments rapidly stops being fun if your debugger is broken!

I am using C++/CLI as a thin wrapper around this vanilla C++ functionality so that I could export it to .NET. All was working fine except that the breakpoints in the C++ code did not work. After some searching I found this post:

The post suggested that I should set the ‘Enable unmanaged code Debugging’ setting of the start-up project (not the C++/CLI project), so I enabled it and the brakepoints started working fine – so big thanks Roman for the tip!

Microsoft C# Coding Style Guidelines & Visual Studio

These days most software developers need deal with more than one software development technology and programming language on a day to day basis. This often means that they have to switch back and forth between coding styles, with this in mind I noticed that although the MS coding guidelines for C# in .NET recommend K&R style braces for code blocks, e.g:


if (sneeze) {


By default Visual Studio’s auto code formatting stuff will format your code with braces on newlines, e.g.:


if (sneeze)


Very interesting indeed, I wonder are there internal coding style conflicts within Microsoft…

Visual Studio, #pragma once not working?

Software development can sometimes be a comical affair, I have just been caught out badly by a strange gotcha – it appeared that #pragma once stopped working on a Visual Studio C++ project on which I have been working.  I was getting plenty of error messages about redefined classes! 


Well it turns out that I had left a copy of one of my header files lying around in one of the project folders.  As pragma once uses a header file’s full path to figure out if it has already opened it, a situation arose whereby both files were included and compile errors flooded in (despite the pragma onces)!


Well removing the (accidential) copy of the header file fixed the problem – boy do I feel stupid, I hope this post may help someone with a similar problem in the future!