我想将在我的应用程序中拍摄的照片(使用 CameraCaptureTask)保存到隔离存储中。当前的问题是 RAM 的消耗,这总是导致OutOfMemoryException。当我将图片加载到 Image-Control 时也会发生这种情况。
我的应用程序最终应该能够拍摄 10 张照片,将它们保存到独立存储中,在图像控件中显示它们,并在必要时永久删除图片。
降低图片的分辨率在逻辑上修复了异常,但这不是我想要的方式。
也许你可以给我一个提示。
这是我的代码:
private CameraCaptureTask ccTask = new CameraCaptureTask();
WriteableBitmap[] imgList = new WriteableBitmap[10];
Random rnd = new Random();
private void addPicture_button_Click(object sender, EventArgs e)
{
ccTask.Show();
ccTask.Completed += ccTask_Completed;
}
void ccTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
WriteableBitmap writeableBitmap = new WriteableBitmap(1600,1200);
writeableBitmap.LoadJpeg(e.ChosenPhoto);
string imageFolder = "Unfaelle";
string datetime = DateTime.Now.ToString().Replace("/","");
datetime = datetime.Replace(":","");
string imageFileName = "Foto_"+datetime+".jpg";
using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.DirectoryExists(imageFolder))
{
isoFile.CreateDirectory(imageFolder);
}
string filePath = System.IO.Path.Combine(imageFolder, imageFileName);
using (var stream = isoFile.CreateFile(filePath))
{
writeableBitmap.SaveJpeg(stream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);
}
}
//now read the image back from storage to show it worked...
BitmapImage imageFromStorage = new BitmapImage();
using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
string filePath = System.IO.Path.Combine(imageFolder, imageFileName);
using (var imageStream = isoFile.OpenFile(
filePath, FileMode.Open, FileAccess.Read))
{
imageFromStorage.SetSource(imageStream);
}
}
Rectangle b = new Rectangle()
{
Width = 100,
Height = 100,
};
Thickness margin = b.Margin;
margin.Left = 10;
margin.Top = 10;
b.Margin = margin;
ImageBrush imgBrush = new ImageBrush();
imgBrush.ImageSource = imageFromStorage;
b.Fill = imgBrush;
b.Tag = System.IO.Path.Combine(imageFolder, imageFileName);
b.Tap += OnTapped;
pictures_wrapPanel.Children.Add(b);
}
}
private void OnTapped(object sender, System.Windows.Input.GestureEventArgs e)
{
Rectangle r = sender as Rectangle;
BitmapImage imageFromStorage = new BitmapImage();
using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
string filePath = r.Tag.ToString();
using (var imageStream = isoFile.OpenFile(
filePath, FileMode.Open, FileAccess.Read))
{
imageFromStorage.SetSource(imageStream);
}
}
img.Source = imageFromStorage;
}
非常感谢,如果有什么不清楚的,欢迎追问。也许有一个更简单的方法来保存照片,我刚刚开始应用程序开发问候丹尼尔
顺便说一句:1600x1200 是 2MP,我降低了分辨率以避免异常,不幸的是它只是延迟了