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

时间:2010-12-14 21:29:00

标签: c# image byte

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

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

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

通过在List

上使用.toArray()构造字节数组
List<byte> encryptedText = new List<byte>();    
pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray())

任何人都可以帮助我吗?我忘了某种格式或什么吗?

必须转换为图像的字节: alt text

 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());
    }

4 个答案:

答案 0 :(得分:9)

尝试这样的事情。处理图像和内存流时,请确保将所有内容都包含在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;
}

答案 1 :(得分:4)

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

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

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

答案 2 :(得分:3)

您应该跳过标题并仅加密图像。 您可以通过将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转换为图像的代码。

我希望这适合你!

答案 3 :(得分:1)

要添加@ Boo的答案,您可以使用Bitmap.LockBits方法获取原始图像数据 - 减去标题。在MSDN page on the BitmapData class上有一个以这种方式操纵图像的例子。