Search code examples
imagefilewindows-phone-8.1isolatedstorage

Save and Retrieve Image to a file on Windows Phone 8.1


I am new to a windows phone programming! My question is how to save and Retrieve Image to a file in windows phone 8.1? I already saw some links , but all of them is in windows phone 7. [http://www.geekchamp.com/tips/all-about-wp7-isolated-storage---read-and-save-images#][1] I wont something like this, but this code only run to windows phone 7

// Create a filename for JPEG file in isolated storage. String tempJPEG = "logo.jpg";

        // Create virtual store and file stream. Check for duplicate tempJPEG files.
        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (myIsolatedStorage.FileExists(tempJPEG))
            {
                myIsolatedStorage.DeleteFile(tempJPEG);
            }

            IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);

            StreamResourceInfo sri = null;
            Uri uri = new Uri(tempJPEG, UriKind.Relative);
            sri = Application.GetResourceStream(uri);

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

            // Encode WriteableBitmap object to a JPEG stream.
            Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);

            //wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
            fileStream.Close();
        }

Solution

  • This is how I save a UI element to png:

                StorageFolder localFolder = ApplicationData.Current.TemporaryFolder;
                StorageFile file = await localFolder.CreateFileAsync(file.png, CreationCollisionOption.ReplaceExisting);
                var renderTargetBitmap = new RenderTargetBitmap();
                await renderTargetBitmap.RenderAsync(element);
                var pixels = await renderTargetBitmap.GetPixelsAsync();
    
                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
                    byte[] bytes = pixels.ToArray();
                    encoder.SetPixelData(
                        BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Straight,
                        (uint)renderTargetBitmap.PixelWidth,
                        (uint)renderTargetBitmap.PixelHeight,
                        DisplayInformation.GetForCurrentView().LogicalDpi,
                        DisplayInformation.GetForCurrentView().LogicalDpi,
                        bytes);
    
                    await encoder.FlushAsync();
                }