通用应用程序缺少WriteableBitmap SaveJpeg

时间:2014-08-16 20:05:24

标签: c# windows-8.1 windows-phone-8.1 dotnet-httpclient win-universal-app

我正在开发一个通用应用程序,在我的共享代码中,我尝试从网上下载图像并将图像保存到LocalFolder。

我正在使用HttpClient从用户给定的URL下载图像并读取客户端响应以保存图像。我使用下面的代码保存,但无法找到可写的SaveJpeg方法。

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

将图像响应保存到具有图像质量%的本地文件夹的最佳方法是什么(对于WP和Windows)。

1 个答案:

答案 0 :(得分:2)

您应该直接保存流,而不是保存BitmapImage

像这样。

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

<强>更新

您可以使用BitmapEncoder并在SetPixelData中传入属性dpi值时使用。

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