Save image in windows phone 8.1 using FileSavePick

2019-02-25 20:06发布

问题:

I want to save an image using File Save Picker . I am using this link to save but it is only for text , how I modify it to save an image?

回答1:

As you have provided the link then I assume that you managed to get StorageFile after Continuation (this is how it works at WP8.1 Runtime).

I also assume that you have a Stream with your image or you know how to obtain such a one. Basing on those two, you can save your image in png format to a file selected by picker for example like this:

public async Task SaveStreamAsync(IRandomAccessStream streamToSave, StorageFile destination)
{
    BitmapDecoder bmpDecoder = await BitmapDecoder.CreateAsync(streamToSave);
    PixelDataProvider pixelData = await bmpDecoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, null, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
    using (var destFileStream = await destination.OpenAsync(FileAccessMode.ReadWrite))
    {
        BitmapEncoder bmpEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destFileStream);
        uint yourWidthAndOrHeight = 1024;
        bmpEncoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, yourWidthAndOrHeight, yourWidthAndOrHeight, 300, 300, pixelData.DetachPixelData());
        await bmpEncoder.FlushAsync();
    }
}

Also please remember to Dispose your streamToSave (and other resources) after finishing working with them.

If you take a look at BitmapEncoder and BitmapDecoder classes, then you will see more options including transformation and various properties.

(I've not tested the code above rough, but hopefully it will work fine)