I’m trying to convert a byte[] to an image in C#. I know this question has been asked on different forums. But none of the answers given on them helped me. To give some context=
I open an image, convert it to a byte[]. I encrypt the byte[]. In the end I still have the byte[] but it has been modified ofc. Now I want to display this again. The byte[] itself consists of 6559 bytes. I try to convert it by doing :
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
and I get this error: Parameter is not valid.
The byte array is constructed by using the .toArray() on a List
List<byte> encryptedText = new List<byte>();
pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray())
;
Can anyone help me? Am I forgetting some kind of format or something ?
The byte that has to be converted to an image :

private void executeAlgoritm(byte[] plainText)
{
// Empty list of bytes
List<byte> encryptedText = new List<byte>();
// loop over all the bytes in the original byte array gotten from the image
foreach (byte value in plainText)
{
// convert it to a bitarray
BitArray myBits = new BitArray(8); //define the size
for (byte x = 0; x < myBits.Count; x++)
{
myBits[x] = (((value >> x) & 0x01) == 0x01) ? true : false;
}
// encrypt the bitarray and return a byte
byte bcipher = ConvertToByte( sdes.IPInvers(sdes.FK(sdes.Shift(sdes.FK(sdes.IP(myBits),keygen.P8(keygen.shift(keygen.P10(txtKey.Text))))),keygen.P8(keygen.shift(keygen.shift(keygen.shift(keygen.P10(txtKey.Text))))))));
// add the byte to the list
encryptedText.Add(bcipher);
}
// show the image by converting the list to an array and the array to an image
pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray());
}
You should skip the header and only encrypt the image.
You can do this by copying the first 54 bytes of your bytearray into the new bytearray in which the encrypted image will be.
Than you loop over all the other bytes in the image and you encrypt them.
Something like this:
In the end you use the code you used to convert a bytearray into an image.
I hope this works for you!