Windows 8 如何将 BitmapImage 作为流打开?
Posted
技术标签:
【中文标题】Windows 8 如何将 BitmapImage 作为流打开?【英文标题】:Windows 8 How to open a BitmapImage as a stream? 【发布时间】:2014-11-05 19:47:02 【问题描述】:在 Windows 8 应用程序中,如何将 BitmapImage 转换为 Stream?我有一个 BitmapImages 列表,我将使用该列表将每个图像上传到服务器,我需要使用 Stream 来做到这一点。那么有没有办法将每个单独的 BitmapImage 转换为 Stream 呢?
【问题讨论】:
【参考方案1】:不,没有。您需要跟踪原始来源或改用WriteableBitmap
。
【讨论】:
我已经玩了一点,我可以将图片保存为列表中的 StorageFile。我不相信我可以做 writeableBitmap。那么在这种情况下,有没有办法将 StorageFile 转换为 Stream?OpenReadAsync
或类似的东西会产生一个流,不是吗?
我已经发布了与 Windows Phone 8.1 相关的答案。【参考方案2】:
检索位图图像:
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("01?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);
【讨论】:
以上是关于Windows 8 如何将 BitmapImage 作为流打开?的主要内容,如果未能解决你的问题,请参考以下文章
如何通过 WPF 中的 SaveFileDialog 保存 BitmapImage?
Windows Phone - 裁剪 BitmapImage [关闭]
在 Windows Phone 和 Silverlight 中将 Image Feed 转换为 BitmapImage