c# – WriteableBitmap上发生OutOfMemoryException
作者:互联网
我正在开发一个Windows Phone应用程序,它可用于将图像上传到Web服务器.我正在从我的设备中选择所有图像到一个List对象.我将所有位图图像逐个转换为byte [].
我的代码
public byte[] ConvertToBytes(BitmapImage bitmapImage)
{
byte[] data = null;
WriteableBitmap wBitmap = null;
using (MemoryStream stream = new MemoryStream())
{
wBitmap = new WriteableBitmap(bitmapImage);
wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
//data = stream.GetBuffer();
data = stream.ToArray();
DisposeImage(bitmapImage);
return data;
}
}
public void DisposeImage(BitmapImage image)
{
if (image != null)
{
try
{
using (MemoryStream ms = new MemoryStream(new byte[] { 0x0 }))
{
image.SetSource(ms);
}
}
catch (Exception ex)
{
}
}
}
从位图转换为字节
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.DirectoryExists("ImagesZipFolder"))
{
//MediaImage mediaImage = new MediaImage();
//mediaImage.ImageFile = decodeImage(new byte[imgStream[0].Length]);
//lstImages.Items.Add(mediaImage);
store.CreateDirectory("ImagesZipFolder");
for (int i = 0; i < imgname.Count(); i++)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(@"ImagesZipFolder\" + imgname[i], FileMode.CreateNew,store))
//using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(@"ImagesZipFolder\text.txt" , System.IO.FileMode.OpenOrCreate, store))
{
// byte[] bytes = new byte[imgStream[i].Length];
byte[] bytes = ConvertToBytes(ImgCollection[i]);
stream.Write(bytes, 0, bytes.Length);
}
}
}
else {
directory = true;
}
}
我的模拟器中有91张图像.当我将所有这些位图图像转换为byte []时,在行上获取以下错误wBitmap = new WriteableBitmap(bitmapImage);
An exception of type ‘System.OutOfMemoryException’ occurred in System.Windows.ni.dll but was not handled in user code
我该怎么做才能解决这个错误?
网络服务
如果我们将大量文件发送到Web服务,是否会出现错误
An exception of type ‘System.OutOfMemoryException’ occurred in System.ServiceModel.ni.dll but was not handled in user code
解决方法:
What can I do to solve this error?
改变你做事的方式,减少记忆.
例如,不是转换每张图片然后上传它们,转换图片,上传图片,转换下一张图片,等等.
如果您真的想一次处理所有图片,可以将字节数组存储在隔离存储中,而不是将它们保存在内存中,并在需要时将其读回.
基本上,重新考虑您的过程并使用存储在给定时间使用更少的内存.
那或要求微软解除Windows Phone的内存限制,但这可能有点棘手.
标签:c,windows-phone-7,windows-phone-8,bitmapimage 来源: https://codeday.me/bug/20190629/1326089.html