WriteableBitmap SaveJpeg missing for universal apps

拟墨画扇 提交于 2019-12-12 17:37:49

问题


I am developing an universal app, in my shared code i am trying to download the image from net and save the image to LocalFolder.

I am using HttpClient to download the images from user given urls and reading the client response to save the image. I am using below code to save, but couldn't able to 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));
        writer.WriteBuffer(buffer);
        bmp.SetSource(ras);
    }
});

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


回答1:


You should save the stream directly instead of saving the BitmapImage.

Something like this.

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

// you can still use this to display it on the UI though
//bmp.SetSource(ras);

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

Update

You can use BitmapEncoder and when pass in property dpi 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();
}


来源:https://stackoverflow.com/questions/25343475/writeablebitmap-savejpeg-missing-for-universal-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!