Windows 8如何以流形式打开BitmapImage?

时间:2014-09-11 18:26:07

标签: c# windows xaml windows-8 windows-8.1

在Windows 8应用中,如何将BitmapImage转换为Stream?我有一个BitmapImages列表,我将使用该List将每个图像上传到服务器,我需要使用Stream来做到这一点。那么有没有办法将每个BitmapImage转换为Stream?

2 个答案:

答案 0 :(得分:0)

不,没有。您需要跟踪原始来源或改为使用WriteableBitmap

答案 1 :(得分:0)

检索位图图片:

public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
{
    if (args.Files.Count > 0)
    {
        var imageFile = args.Files[0] as StorageFile;
        // Ensure the stream is disposed once the image is loaded
        using (IRandomAccessStream fileStream = await imageFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
        {
            // Set the image source to the selected bitmap
            BitmapImage bitmapImage = new BitmapImage();

            await bitmapImage.SetSourceAsync(fileStream);
            ImageControl.Source = bitmapImage;

            await _viewModel.Upload(imageFile);
        }               
    }
}

创建文件流:

internal async Task Upload(Windows.Storage.StorageFile file)
{
    var fileStream = await file.OpenAsync(FileAccessMode.Read);
    fileStream.Seek(0);

    var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
    await reader.LoadAsync((uint)fileStream.Size);

    Globals.MemberId = ApplicationData.Current.LocalSettings.Values[Globals.PROFILE_KEY];
    var userName = "Rico";
    var sex = 1;
    var url = string.Format("{0}{1}?memberid={2}&name={3}&sex={4}", Globals.URL_PREFIX, "api/Images", Globals.MemberId, userName,sex);
    byte[] image = new byte[fileStream.Size];

    await UploadImage(image, url);
}

从图片中创建内存流:

public async Task UploadImage(byte[] image, string url)
{
    Stream stream = new System.IO.MemoryStream(image);
    HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());

    Uri resourceAddress = null;
    Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress);
    Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress);
    request.Content = streamContent;

    var httpClient = new Windows.Web.Http.HttpClient();
    var cts = new CancellationTokenSource();
    Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token);
}