如何将图像转换为字节数组而不将其类型转换为JPEG

时间:2013-10-15 21:28:34

标签: c# xml-serialization windows-phone

我为Windows手机平台编写了一个解密图像的应用程序。为了测试应用程序,我在windows classic(桌面)平台上有一个代码,它通过TCP连接与windows phone app进行通信。现在我在Windows手机应用程序中有一个图像被解密,我想验证它是否与原始图像相同(加密前)。使用XMLSerialization我不能在TCP连接上发送Image类型;所以我使用这段代码将其转换为字节:

BitmapImage bitmapImage = image.Source as BitmapImage;
using (MemoryStream ms = new MemoryStream())
{
    WriteableBitmap btmMap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);

    Extensions.SaveJpeg(btmMap, ms, bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

    bytes = ms.ToArray();
}

但是,我得到的字节与原始图像字节不匹配,因为图像被编码为Jpeg。即使在测试端,我将原始图像转换为jpeg格式,字节也不匹配。但是,当我将字节发送到WinPhone应用程序并将它们转换为Jpeg时,它们是相同的。如何在不将图像转换为Jpeg格式的情况下获取字节?

1 个答案:

答案 0 :(得分:0)

波纹管代码对我来说很好。

public static byte[] imageToByteArray(System.Drawing.Image sourceImage)
    {
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

        sourceImage.Save(memoryStream, sourceImage.RawFormat);

        return memoryStream.ToArray();
    }
相关问题