本文整理汇总了C#中Stream.AsRandomAccessStream方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.AsRandomAccessStream方法的具体用法?C# Stream.AsRandomAccessStream怎么用?C# Stream.AsRandomAccessStream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Stream
的用法示例。
在下文中一共展示了Stream.AsRandomAccessStream方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SavePngAsync
/// <summary>
/// Encodes a WriteableBitmap object into a PNG stream.
/// </summary>
/// <param name="writeableBitmap">The writeable bitmap.</param>
/// <param name="outputStream">The image data stream.</param>
/// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
public static async Task SavePngAsync(this WriteableBitmap writeableBitmap, Stream outputStream)
{
#if WINDOWS_PHONE
WriteHeader(outputStream, writeableBitmap);
WritePhysics(outputStream);
////WriteGamma(outputStream);
WriteDataChunks(outputStream, writeableBitmap);
WriteFooter(outputStream);
outputStream.Flush();
await Task.FromResult(0);
#else
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outputStream.AsRandomAccessStream());
var pixels = writeableBitmap.PixelBuffer.ToArray();
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, ResolutionDpi, ResolutionDpi, pixels);
await encoder.FlushAsync();
#endif
}
示例2: ConvertToSoftwareBitmap
public async Task<SoftwareBitmap> ConvertToSoftwareBitmap(Stream stream)
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream());
SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();
SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
return softwareBitmapBGR8;
}
示例3: SavePngAsync
/// <summary>
/// Encodes a WriteableBitmap object into a PNG stream.
/// </summary>
/// <param name="renderTargetBitmap">The render target bitmap.</param>
/// <param name="outputStream">The image data stream.</param>
/// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
public static async Task SavePngAsync(this RenderTargetBitmap renderTargetBitmap, Stream outputStream)
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outputStream.AsRandomAccessStream());
var pixels = (await renderTargetBitmap.GetPixelsAsync()).ToArray();
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, ResolutionDpi, ResolutionDpi, pixels);
await encoder.FlushAsync();
}
示例4: PlayAsync
public async Task PlayAsync(Stream speechStream, string contentFormat)
{
if (speechStream == null) throw new ArgumentNullException(nameof(speechStream));
if (contentFormat == null) throw new ArgumentNullException(nameof(speechStream));
var media = new MediaElement();
media.SetSource(speechStream.AsRandomAccessStream(), contentFormat);
media.Play();
await Task.CompletedTask;
}
示例5: SaveJpegAsync
/// <summary>
/// Encodes a WriteableBitmap object into a JPEG stream, with parameters for setting the target quality of the JPEG file.
/// </summary>
/// <param name="writeableBitmap">The WriteableBitmap object.</param>
/// <param name="outputStream">The image data stream.</param>
/// <param name="quality">This parameter represents the quality of the JPEG photo with a range between 0 and 100, with 100 being the best photo quality. We recommend that you do not fall lower than a value of 70. because JPEG picture quality diminishes significantly below that level. </param>
/// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
public static async Task SaveJpegAsync(this WriteableBitmap writeableBitmap, Stream outputStream, int quality)
{
var propertySet = new BitmapPropertySet
{
{ "ImageQuality", new BitmapTypedValue(quality, PropertyType.Single) }
};
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream.AsRandomAccessStream(), propertySet);
var pixels = writeableBitmap.PixelBuffer.ToArray();
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, ResolutionDpi, ResolutionDpi, pixels);
await encoder.FlushAsync();
}
示例6: ByteStream
/// <summary>
/// Instantiates a new instance <see cref="ByteStream"/> from a <see cref="Stream"/>.
/// </summary>
/// <msdn-id>hh162754</msdn-id>
/// <unmanaged>HRESULT MFCreateMFByteStreamOnStreamEx([In] IUnknown* punkStream,[Out] IMFByteStream** ppByteStream)</unmanaged>
/// <unmanaged-short>MFCreateMFByteStreamOnStreamEx</unmanaged-short>
public ByteStream(Stream sourceStream)
{
this.sourceStream = sourceStream;
#if WIN8METRO
var randomAccessStream = sourceStream.AsRandomAccessStream();
randomAccessStreamCom = new ComObject(Marshal.GetIUnknownForObject(randomAccessStream));
MediaFactory.CreateMFByteStreamOnStreamEx(randomAccessStreamCom, this);
#else
streamProxy = new ComStreamProxy(sourceStream);
IByteStream localStream;
MediaFactory.CreateMFByteStreamOnStream(ComStream.ToIntPtr(streamProxy), out localStream);
NativePointer = ((ByteStream) localStream).NativePointer;
#endif
}
示例7: ConvertFromEncodedStream
public async Task<object> ConvertFromEncodedStream(Stream encodedStream, int width, int height)
{
if (encodedStream == null)
return null;
var image = new WriteableBitmap(width, height);
encodedStream.Seek(0, SeekOrigin.Begin);
await image.SetSourceAsync(encodedStream.AsRandomAccessStream());
return image;
//var writeableImage = new WriteableBitmap(image.PixelWidth, image.PixelHeight);
//image.SetSource(encodedStream.AsRandomAccessStream());
//return writeableImage;
}
示例8: CN1Media
public CN1Media(Stream s, string mime, java.lang.Runnable onComplete, Canvas cl)
{
this.cl = cl;
using (AutoResetEvent are = new AutoResetEvent(false))
{
SilverlightImplementation.dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
elem = new MediaElement();
cl.Children.Add(elem);
elem.MediaOpened += elem_MediaOpened;
elem.SetSource(s.AsRandomAccessStream(), "");
video = mime.StartsWith("video");
this.onComplete = onComplete;
elem.MediaEnded += elem_MediaEnded;
are.Set();
}).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
are.WaitOne();
}
}
示例9: CallWithBinary
public async Task<CallRet> CallWithBinary(string url, HttpMediaTypeHeaderValue contentType, Stream body, long length)
{
Debug.WriteLine("Client.PostWithBinary ==> URL: {0} Length:{1}", url, length);
try
{
HttpClient client = new HttpClient();
body.Position = 0;
HttpStreamContent streamContent = new HttpStreamContent(body.AsRandomAccessStream());
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
req.Content = streamContent;
SetAuth(req,client, body);
var resp = await client.SendRequestAsync(req);
return await HandleResult(resp);
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
return new CallRet(Windows.Web.Http.HttpStatusCode.BadRequest, e);
}
}
示例10: RendererImage
private static void RendererImage(Stream stream, SvgImageRendererSettings settings)
{
var svg = settings.Document;
var viewPort = svg.RootElement.ViewPort;
if (!viewPort.HasValue) throw new ArgumentException(nameof(settings));
var width = viewPort.Value.Width;
var height = viewPort.Value.Height;
var device = CanvasDevice.GetSharedDevice();
using (var offScreen = new CanvasRenderTarget(device, width, height, settings.Scaling * 96.0F))
{
using (var renderer = new Win2dRenderer(offScreen, svg))
using (var session = offScreen.CreateDrawingSession())
{
session.Clear(Colors.Transparent);
renderer.Render(width, height, session);
}
offScreen.SaveAsync(stream.AsRandomAccessStream(), (CanvasBitmapFileFormat)settings.Format, settings.Quality).AsTask().GetAwaiter().GetResult();
}
}
示例11: SaveCoverImages
protected bool SaveCoverImages(string bookID, Stream imageStream)
{
var @event = new AutoResetEvent(false);
bool result = false;
((Action)(() =>
{
try
{
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(imageStream.AsRandomAccessStream());
using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var iconImageFile = isoStorage.CreateFile(ModelExtensions.GetBookCoverPath(bookID)))
{
bitmapImage.SaveJpeg(iconImageFile, 300, 300, true);
}
using (var coverImageFile = isoStorage.CreateFile(ModelExtensions.GetBookFullCoverPath(bookID)))
{
bitmapImage.SaveJpeg(coverImageFile, bitmapImage.PixelWidth, bitmapImage.PixelHeight, false);
}
}
result = true;
}
catch (Exception)
{
result = false;
}
finally
{
@event.Set();
}
})).OnUIThread();
@event.WaitOne();
return result;
}
示例12: SavePictureToDiskWINRT
public async void SavePictureToDiskWINRT(Stream imgStream, string Id, bool OverwriteIfExist = false)
{
var inStream = imgStream.AsRandomAccessStream();
var fileBytes = new byte[inStream.Size];
using (DataReader reader = new DataReader(inStream))
{
await reader.LoadAsync((uint)inStream.Size);
reader.ReadBytes(fileBytes);
}
var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(Id+".jpg", Windows.Storage.CreationCollisionOption.ReplaceExisting);
using (var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
{
var outStream = fs.GetOutputStreamAt(0);
var dataWriter = new DataWriter(outStream);
dataWriter.WriteBytes(fileBytes);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
await outStream.FlushAsync();
outStream.Dispose();
fs.Dispose();
}
}
示例13: ResizeImageAsync
public Task<byte[]> ResizeImageAsync(Stream imageStream, double height, double width)
{
return Task.Run(async () =>
{
try
{
var decoder = await BitmapDecoder.CreateAsync(imageStream.AsRandomAccessStream());
InMemoryRandomAccessStream resizedStream = new InMemoryRandomAccessStream();
if (decoder.OrientedPixelHeight > height || decoder.OrientedPixelWidth > width)
{
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
double widthRatio = width / decoder.OrientedPixelWidth;
double heightRatio = height / decoder.OrientedPixelHeight;
// Use whichever ratio had to be sized down the most to make sure the image fits within our constraints.
double scaleRatio = Math.Min(widthRatio, heightRatio);
uint aspectHeight = (uint)Math.Floor(decoder.OrientedPixelHeight * scaleRatio);
uint aspectWidth = (uint)Math.Floor(decoder.OrientedPixelWidth * scaleRatio);
encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
encoder.BitmapTransform.ScaledHeight = aspectHeight;
encoder.BitmapTransform.ScaledWidth = aspectWidth;
try
{
// write out to the stream
// might fail cause https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmapencoder.bitmaptransform.aspx
await encoder.FlushAsync();
}
catch (Exception ex)
{
//from http://stackoverflow.com/questions/38617761/bitmapencoder-flush-throws-argument-exception/38633258#38633258
if (ex.HResult.ToString() == "WINCODEC_ERR_INVALIDPARAMETER" || ex.HResult == -2147024809)
{
resizedStream = new InMemoryRandomAccessStream();
BitmapEncoder pixelencoder =
await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
BitmapTransform transform = new BitmapTransform
{
InterpolationMode = BitmapInterpolationMode.Fant,
ScaledHeight = aspectHeight,
ScaledWidth = aspectWidth
};
var provider = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);
var pixels = provider.DetachPixelData();
pixelencoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
aspectWidth,
aspectHeight, decoder.DpiX, decoder.DpiY, pixels);
try
{
await pixelencoder.FlushAsync();
}
catch (Exception ex2)
{
LogHelper.Instance.LogException(ex2);
return null;
}
}
else
{
LogHelper.Instance.LogException(ex);
return null;
}
}
// Reset the stream location.
resizedStream.Seek(0);
// Writes the image byte array in an InMemoryRandomAccessStream
using (DataReader reader = new DataReader(resizedStream.GetInputStreamAt(0)))
{
var bytes = new byte[resizedStream.Size];
await reader.LoadAsync((uint)resizedStream.Size);
reader.ReadBytes(bytes);
return bytes;
}
}
imageStream.Seek(0, SeekOrigin.Begin);
using (var memoryStream = new MemoryStream())
{
imageStream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
catch (Exception ex)
{
LogHelper.Instance.Log(LogLevel.Warning, "Download.cs", "ResizeImageAsync failed", ex);
}
return null;
});
}
示例14: UploadPhoto
/// <summary>
/// Uploads the photo.
/// </summary>
/// <param name="stream">The memory stream.</param>
/// <param name="localPath">The local path.</param>
/// <param name="caption">The caption.</param>
/// <param name="categoryId">The id of the assocaited category.</param>
/// <returns>The uploaded photo.</returns>
public async Task<Photo> UploadPhoto(Stream stream, string localPath, string caption, string categoryId)
{
try
{
var sasContracts = await GetSasUrls();
// Upload photos into azure
foreach (var sasContract in sasContracts)
{
var blob =
new CloudBlockBlob(
new Uri($"{sasContract.FullBlobUri}{sasContract.SasToken}"));
var sideLength = sasContract.SasPhotoType.ToSideLength();
var resizedStream = await BitmapTools.Resize(
stream.AsRandomAccessStream(), sideLength,
sideLength);
await blob.UploadFromStreamAsync(resizedStream);
}
var photoContract = new PhotoContract
{
CategoryId = categoryId,
Description = caption,
OSPlatform = AnalyticsInfo.VersionInfo.DeviceFamily,
User = AppEnvironment.Instance.CurrentUser.ToDataContract(),
ThumbnailUrl =
sasContracts.FirstOrDefault(c => c.SasPhotoType == PhotoTypeContract.Thumbnail)?
.FullBlobUri.ToString(),
StandardUrl =
sasContracts.FirstOrDefault(c => c.SasPhotoType == PhotoTypeContract.Standard)?
.FullBlobUri.ToString(),
HighResolutionUrl =
sasContracts.FirstOrDefault(c => c.SasPhotoType == PhotoTypeContract.HighRes)?
.FullBlobUri.ToString()
};
var responsePhotoContract =
await _mobileServiceClient.InvokeApiAsync<PhotoContract, PhotoContract>("Photo",
photoContract,
HttpMethod.Post,
null);
return responsePhotoContract.ToDataModel();
}
catch (Exception e)
{
throw new ServiceException("UploadPhoto error", e);
}
}
示例15: FromStreamAsync
public static async Task<BandImage> FromStreamAsync(Stream stream)
{
#if __ANDROID__
var image = await BitmapFactory.DecodeStreamAsync(stream);
return FromBitmap(image);
#elif __IOS__
var image = await Task.Run(() =>
{
using (var data = NSData.FromStream(stream))
{
return NativeBitmap.LoadFromData(data);
}
});
return FromUIImage(image);
#elif WINDOWS_PHONE_APP
using (var fileStream = stream.AsRandomAccessStream())
{
var bitmap = new NativeBitmap(1, 1);
await bitmap.SetSourceAsync(fileStream);
return FromWriteableBitmap(bitmap);
}
#else // PORTABLE
return null;
#endif
}