尝试将图片保存到MediaLibrary
时,我收到以下错误
Microsoft.Xna.Framework.ni.dll中发生了'System.InvalidOperationException'类型的异常,但未在用户代码中处理
这是我正在使用的代码
if (SourceImage != null) // Source Image is WriteableBitmap
{
var imageArray = SourceImage.ToByteArray(); // WriteableBitmapExWinPhone (extension method)
var res = await SavePhotoToImageHub(imageArray);
await ShowMessage(res ? AppResources.MEDIA_LIBRARY_SUCCESS_MESSAGE : AppResources.MEDIA_LIBRARY_FAILURE_MESSAGE);
}
使用的方法是
private Task<bool> SavePhotoToImageHub(byte[] imageArray)
{
using (var mediaLibrary = new MediaLibrary())
{
var fileName = string.Format("Gs{0}.jpg", Guid.NewGuid());
var picture = mediaLibrary.SavePicture(fileName, imageArray);
if (picture.Name.Contains(fileName)) return Task.FromResult(true);
}
return Task.FromResult(false);
}
我也试过流而不是字节数组。
答案 0 :(得分:6)
您需要检查的第一件事是您是否已将ID_CAP_MEDIALIB_PHOTO添加到您的应用清单。
第二件事是流 - 您尝试将其重置为开头吗?这种方法对我有用:
private bool SavePhotoToImageHub(WriteableBitmap bmp)
{
using (var mediaLibrary = new MediaLibrary())
{
using (var stream = new MemoryStream())
{
var fileName = string.Format("Gs{0}.jpg", Guid.NewGuid());
bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
var picture = mediaLibrary.SavePicture(fileName,stream);
if (picture.Name.Contains(fileName)) return true;
}
}
return false;
}