M_K*_*M_K 4 c# silverlight windows-phone-7
编辑:我一直得到OutOfMemoryException未处理,我认为这是我如何将图像保存到隔离存储,我认为这是我可以解决我的问题,如何在保存之前减小图像的大小?(添加了我保存图片的代码)
我从隔离存储打开图像有时超过100个图像,我想循环它们的图像,但我得到一个OutOfMemory Exception时,有大约100到150个图像加载到故事板.如何处理此异常,我已经降低了图像的分辨率.如何处理此异常并阻止我的应用程序崩溃?
我在这条线上得到了例外
image.SetSource(isStoreTwo.OpenFile(projectFolder + "\\MyImage" + i + ".jpg", FileMode.Open, FileAccess.Read));//images from isolated storage
这是我的代码
private void OnLoaded(object sender, RoutedEventArgs e)
{
IsolatedStorageFile isStoreTwo = IsolatedStorageFile.GetUserStoreForApplication();
try
{
storyboard = new Storyboard
{
//RepeatBehavior = RepeatBehavior.Forever
};
var animation = new ObjectAnimationUsingKeyFrames();
Storyboard.SetTarget(animation, projectImage);
Storyboard.SetTargetProperty(animation, new PropertyPath("Source"));
storyboard.Children.Add(animation);
for (int i = 1; i <= savedCounter; i++)
{
BitmapImage image = new BitmapImage();
image.SetSource(isStoreTwo.OpenFile(projectFolder + "\\MyImage" + i + ".jpg", FileMode.Open, FileAccess.Read));//images from isolated storage
var keyframe = new DiscreteObjectKeyFrame
{
KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(100 * i)),
Value = image
};
animation.KeyFrames.Add(keyframe);
}
}
catch (OutOfMemoryException exc)
{
//throw;
}
Resources.Add("ProjectStoryBoard", storyboard);
storyboard.Begin();
}
Run Code Online (Sandbox Code Playgroud)
编辑 这是我将图像保存到隔离存储的方式,我认为这是我可以解决问题的地方,如何将图像保存到隔离存储时减小图像的大小?
void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
string fileName = folderName+"\\MyImage" + savedCounter + ".jpg";
try
{
// Save picture to the library camera roll.
//library.SavePictureToCameraRoll(fileName, e.ImageStream);
// Set the position of the stream back to start
e.ImageStream.Seek(0, SeekOrigin.Begin);
// Save picture as JPEG to isolated storage.
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
{
// Initialize the buffer for 4KB disk pages.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the image to isolated storage.
while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
}
finally
{
// Close image stream
e.ImageStream.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
如果你能帮助我,我将不胜感激.
您的图像在磁盘上的大小并不重要,因为当您将它们加载到内存中时,它们将被解压缩.图像所需的内存大约是(stride * height).strideis width * bitsPerPixel)/8,然后向上舍入到4个字节的下一个倍数.因此,每像素1024x768和24位的图像将占用大约2.25 MB.
您应该弄清楚图像的大小,未压缩,并使用该数字来确定内存要求.
您正在获取OutOfMemory异常,因为您要同时将所有图像存储在内存中以创建StoryBoard.我认为您无法克服图像需要在屏幕上显示的未压缩位图大小.
因此,为了解决这个问题,我们必须考虑您的目标,而不是尝试修复错误.如果您的目标是每X ms按顺序显示一个新图像,那么您有几个选项.
继续使用StoryBoards,但使用OnCompleted事件链接它们.这样您就不必一次创建它们,但只能生成接下来的几个.如果你每100毫秒更换图像,它可能不够快.
使用我在这里的答案中提到的CompositionTarget.Rendering .如果您只是预加载下一个内存,则可能占用最少的内存(而不是像当前解决方案那样预先加载它们).您需要手动检查已用时间.
重新思考你在做什么.如果你在人们可能有更多选择之后说出你的想法.