store image into isolated storage in windows phone

2020-02-14 05:47发布

问题:

Basically I am using Visual Studio/Expression Blend to do my app. Its works as in the user can select the picture that he/she wants to edit and after editing the user just had to click the save button and the edited image will be save in isolated storage but I just could not command the save button to save the image into the isolated storage so hope someone will help me with it with some sample codes thanks a lot in advance.

I tried with the code below but when I press the save button there's a null reference error. My thinking is that when you press save, the app does not know which image to save into the isolated storage and not really sure my thinking is right. Can anyone please help me with this. Thanks a lot.

private void btnSave_Click(object sender, RoutedEventArgs e)
{
    String tempJPEG = "TempJPEG";

    var myStore = IsolatedStorageFile.GetUserStoreForApplication();
    if (myStore.FileExists(tempJPEG))
    {
        myStore.DeleteFile(tempJPEG);
    }

    IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJPEG);

    Uri uri = new Uri("TestImage.jpg", UriKind.Relative);
    StreamResourceInfo sri = Application.GetResourceStream(uri);

    BitmapImage bitmap = new BitmapImage();
    bitmap.CreateOptions = BitmapCreateOptions.None; 
    bitmap.SetSource(sri.Stream);
    WriteableBitmap wb = new WriteableBitmap(bitmap);

    Extensions.SaveJpeg(wb, myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
    myFileStream.Close();

回答1:

This is the working version of the code

private void saveButtonClick(object sender, RoutedEventArgs e)
{
    try
    {
        using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (isf.FileExists("myImage.jpg"))
                isf.DeleteFile("myImage.jpg");
            using (var isfs = isf.CreateFile("myImage.jpg"))
            {
                var bmp = new WriteableBitmap(myImageElement,
                                myImageElement.RenderTransform);
                bmp.SaveJpeg(isfs, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

Here myImageElement is the Image Element in which you display the image.