将图片转换为字节数组时的Outofmemory异常

时间:2014-01-20 16:34:54

标签: c# image windows-phone-8 stream out-of-memory

我正在使用Windows Phone,我需要将手机中的图像转换为字节数组,但问题是VisualStudio会抛出OutOfMemory异常。

有没有办法避免这个错误?还是另一种方式?

public static byte[] GetBytes(Picture p)
{
    byte[] buffer=new byte[p.GetImage().Length];
    p.GetImage().Read(buffer, 0, buffer.Length);
    return buffer;
}

3 个答案:

答案 0 :(得分:0)

图片对于内存而言太大了。使用Stream中的System.IO对其进行流式处理并保存。这是最有效的。

答案 1 :(得分:0)

您需要使用MemoryStream,例如:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
 MemoryStream ms = new MemoryStream();
 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
 return  ms.ToArray();
}

请参阅How to convert image in byte array

答案 2 :(得分:0)

好的,我找到了另一种上传图片的方法,现在它不会抛出异常。我决定用大块上传文件,就像Steven Mills一样。我想感谢你们的帮助。