简体   繁体   English

Windows 8如何打开BitmapImage作为流?

[英]Windows 8 How to open a BitmapImage as a stream?

In a Windows 8 app, how do I convert a BitmapImage to a Stream? 在Windows 8应用中,如何将BitmapImage转换为流? I have a List of BitmapImages and I'm going to use that List to upload each image to a server and I need to use a Stream to do that. 我有一个BitmapImages列表,我将使用该列表将每个图像上传到服务器,并且需要使用Stream来做到这一点。 So is there a way to convert each individual BitmapImage into a Stream? 那么有没有办法将每个单独的BitmapImage转换为Stream?

No, there isn't. 不,没有。 You need to track the original sources or use a WriteableBitmap instead. 您需要跟踪原始源或改用WriteableBitmap

Retrieve the bitmap image: 检索位图图像:

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

Create the file stream: 创建文件流:

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

Create a memory stream from the image: 从映像创建内存流:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM