Stephan Ronald
Stephan Ronald

Reputation: 1405

Exception while trying to save an image into Media Library in Windows Phone 8

While trying to save an image into MediaLibrary i am getting the following error

An exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.ni.dll but was not handled in user code

Here is the code i am using

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);
}

The method using is

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);
}

I also tried stream instead of byte array.

Upvotes: 1

Views: 1996

Answers (1)

Igor Ralic
Igor Ralic

Reputation: 15006

The first thing you need to check is whether you have added ID_CAP_MEDIALIB_PHOTO to your app manifest.

The second thing is the stream - have you tried resetting it to the beginning? This method worked for me:

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;
    }

Upvotes: 6

Related Questions