WriteableBitmap SaveJpeg is missing for universal apps

I am developing a generic app, in my shared code, I am trying to load an image from the net and save the image to LocalFolder.

I am using HttpClient to load images from user-defined urls and read the client response to save the image. I am using below code to save but couldn't find Writeable SaveJpeg method.

HttpResponseMessage response = await httpClient.GetAsync(imageUri);
await Task.Run(async () =>
    if (response.IsSuccessStatusCode)
        // save image locally
        StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Images", CreationCollisionOption.OpenIfExists);

        BitmapImage bmp = new BitmapImage();
        var buffer = await response.Content.ReadAsBufferAsync();

        InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
        DataWriter writer = new DataWriter(ras.GetOutputStreamAt(0));


What is the best way to store the imageresponse in localfolder with% image quality (for WP and Windows).


source to share

1 answer

You must save the stream directly instead of saving BitmapImage


Something like that.

var ras = new InMemoryRandomAccessStream();
var writer = new DataWriter(ras);
await writer.StoreAsync();
var inputStream = ras.GetInputStreamAt(0);

// you can still use this to display it on the UI though

// write the picture into this folder
var storageFile = await folder.CreateFileAsync("image1.jpg", CreationCollisionOption.GenerateUniqueName);
using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
    await RandomAccessStream.CopyAndCloseAsync(inputStream, storageStream.GetOutputStreamAt(0));



You can use BitmapEncoder

and when passing the dpi property values ​​in SetPixelData


using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, storageStream);
    var pixelStream = yourWriteableBitmap.PixelBuffer.AsStream();
    var pixels = new byte[pixelStream.Length];
    await pixelStream.ReadAsync(pixels, 0, pixels.Length);

    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)yourWriteableBitmap.PixelWidth, (uint)yourWriteableBitmap.PixelHeight, 48, 48, pixels);
    await encoder.FlushAsync();




All Articles