修改数组后,将字节数组转换为c#中的Image

我正在尝试将字节[]转换为C#中的图像。 我知道这个问题已经在不同的论坛上提出过。 但是他们给出的答案都没有帮助我。 给出一些上下文=我打开一个图像,将其转换为byte []。 我加密字节[]。 最后我仍然有字节[]但它已被修改为ofc。 现在我想再次显示它。 byte []本身由6559个字节组成。 我尝试通过以下方式转换它:

public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return returnImage; } 

我收到此错误:参数无效。

通过在List上使用.toArray()构造字节数组

 List encryptedText = new List(); pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray()) 

;

谁能帮我? 我忘记了某种格式或什么?

必须转换为图像的字节: 替代文字

  private void executeAlgoritm(byte[] plainText) { // Empty list of bytes List encryptedText = new List(); // 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 > 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()); } 

您应该跳过标题并仅加密图像。 您可以通过将bytearray的前54个字节复制到加密图像所在的新bytearray中来完成此操作。 比你循环遍历图像中的所有其他字节并加密它们。 像这样的东西:

  for (int i = 0; i < img.Length; i++) { if (i < 54) { //copy the first 54 bytes from the header _cyph[i] = img[i]; }else{ //encrypt all the other bytes _cyph[i] = encrypt(img[i]); } } 

最后,您使用用于将bytearray转换为图像的代码。

我希望这适合你!

尝试这样的事情。 处理图像和内存流时,请务必将所有内容包装在using语句中,以确保正确放置对象。

 public static Image CreateImage(byte[] imageData) { Image image; using (MemoryStream inStream = new MemoryStream()) { inStream.Write(imageData, 0, imageData.Length); image = Bitmap.FromStream(inStream); } return image; } 

根据问题和评论,我猜你正在修改与图像标题相关的字节。 您无法修改这些字节(使用加密方法)并且仍然可以加载图像。

确保您没有更改标头字节。

您可以在google / wikipedia上找到有关标题格式的信息。

要添加@ Boo的答案,您可以使用Bitmap.LockBits方法获取原始图像数据 – 减去标题。 有一个在BitmapData类的MSDN页面上以这种方式操作图像的示例。