0

I want to open a Bitmap File in C# as an array of bytes, and replace certain bytes within that array, and rewrite the Byte array back to disk as a bitmap again.

My current approach is to read into a byte[] array, then convert that array to a list to begin editing individual bytes.

originalBytes = File.ReadAllBytes(path);
List<byte> listBytes = new List<Byte>(originalBytes);

How does one go about replacing every nth byte in the array with a user configured/different byte each time and rewriting back to file?

2
  • Are you aware, that you are using byte, which is not the same as bit? Please clarify your question. Commented Jan 31, 2017 at 19:13
  • Apologies for the error, it has been clarified. I'd like to replace bytes within the array, for example replace a byte with an ASCII byte character (stenography). Commented Jan 31, 2017 at 19:17

3 Answers 3

4

no need in List<byte>

replaces every n-th byte with customByte

var n = 5;
byte customByte = 0xFF;

var bytes = File.ReadAllBytes(path);

for (var i = 0; i < bytes.Length; i++)
{
    if (i%n == 0)
    {
        bytes[i] = customByte;
    }
}

File.WriteAllBytes(path, bytes);
Sign up to request clarification or add additional context in comments.

7 Comments

Agree. Beat me to it.
What if I wanted to change the byte each time?
incrementing i by n would make it a bit faster
@ThomasD. yep, you are right. That would probably be a better practice.
@Anton8000 each time what? run the code as many times as you want. But consider to increment i by n as @ThomasD. wrote if performance matters
|
2

Assuming that you want to replace every nth byte with the same new byte, you could do something like this (shown for every 3rd byte):

int n = 3;
byte newValue = 0xFF;
for (int i = n; i < listBytes.Count; i += n)
{
  listBytes[i] = newValue;
}

File.WriteAllBytes(path, listBytes.ToArray());

Of course, you could also do this with a fancy LINQ expression which would be harder to read i guess.

Comments

1

Technically, you can implement something like this:

 // ReadAllBytes returns byte[] array, we have no need in List<byte>
 byte[] data = File.ReadAllBytes(path);

 // starting from 0 - int i = 0 - will ruin BMP header which we must spare 
 // if n is small, you may want to start from 2 * n, 3 * n etc. 
 // or from some fixed offset
 for (int i = n; i < data.Length; i += n)
   data[i] = yourValue;

 File.WriteAllBytes(path, data);

Please notice, that Bitmap file has a header

https://en.wikipedia.org/wiki/BMP_file_format

that's why I've started loop from n, not from 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.