![](/img/trans.png)
[英]Is there a way to convert a System.IO.Stream to a Windows.Storage.Streams.IRandomAccessStream?
[英]C# UWP Converting from System.IO.Stream to Windows.Storage.Streams.IRandomAccessStreamWithContentType
所以我試圖獲得IRandomAccessStreamWithContentType但不能,因為我得到異常:
"This IRandomAccessStream does not support the CloneStream method because it requires cloning and this stream does not support cloning."
這發生在以下代碼的最后一行:
PixelDataProvider pix = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.IgnoreExifOrientation,
ColorManagementMode.ColorManageToSRgb);
byte[] pixels = pix.DetachPixelData();
Stream pixStream = cropBmp.PixelBuffer.AsStream();
pixStream.Write(pixels, 0, (int)(width * height * 4));
IRandomAccessStream iStream= pixStream.AsRandomAccessStream(); //dafaq with streams
RandomAccessStreamReference iReferenceStream= RandomAccessStreamReference.CreateFromStream(iStream);
IRandomAccessStreamWithContentType newStream = await iReferenceStream.OpenReadAsync();
有沒有解決方法或什么?
編輯1
我也試過這種方式,仍然無法正常工作。 (但現在我得到null而不是克隆失敗了)
InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
await ras.WriteAsync(pixels.AsBuffer());
RandomAccessStreamReference iReferenceStream = RandomAccessStreamReference.CreateFromStream(ras);
IRandomAccessStreamWithContentType newStream = await iReferenceStream.OpenReadAsync();
從您的代碼中,您似乎使用了BitmapDecoder
。 BitmapDecoder
提供對位圖容器數據的讀訪問以及來自第一幀的數據。
我們應該能夠為編碼器創建一個新的InMemoryRandomAccessStream
來寫入並調用BitmapEncoder.CreateForTranscodingAsync
,傳入內存中的流和解碼器對象。
例如:
Windows.Storage.Streams.IRandomAccessStream random = await Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/sunset.jpg")).OpenReadAsync();
Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(random);
Windows.Graphics.Imaging.PixelDataProvider pixelData = await decoder.GetPixelDataAsync();
byte[] buffer = pixelData.DetachPixelData();
InMemoryRandomAccessStream inMemoryRandomAccessStream = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryRandomAccessStream, decoder);
encoder.BitmapTransform.ScaledWidth = 320;
encoder.BitmapTransform.ScaledHeight = 240;
await encoder.FlushAsync();
inMemoryRandomAccessStream.Seek(0);
random.Seek(0);
BitmapImage bitmapImage = new BitmapImage();
RandomAccessStreamReference iReferenceStream = RandomAccessStreamReference.CreateFromStream(inMemoryRandomAccessStream);
IRandomAccessStreamWithContentType newStream = await iReferenceStream.OpenReadAsync();
bitmapImage.SetSource(newStream);
MyImage.Source = bitmapImage;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.