当前位置: 首页>>代码示例>>C#>>正文


C# InMemoryRandomAccessStream.FlushAsync方法代码示例

本文整理汇总了C#中Windows.Storage.Streams.InMemoryRandomAccessStream.FlushAsync方法的典型用法代码示例。如果您正苦于以下问题:C# InMemoryRandomAccessStream.FlushAsync方法的具体用法?C# InMemoryRandomAccessStream.FlushAsync怎么用?C# InMemoryRandomAccessStream.FlushAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Windows.Storage.Streams.InMemoryRandomAccessStream的用法示例。


在下文中一共展示了InMemoryRandomAccessStream.FlushAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ImageToBytes

        private async Task<byte[]> ImageToBytes(IRandomAccessStream sourceStream)
        {
            byte[] imageArray;

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);

            var transform = new BitmapTransform { ScaledWidth = decoder.PixelWidth, ScaledHeight = decoder.PixelHeight };
            PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Rgba8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.RespectExifOrientation,
                ColorManagementMode.DoNotColorManage);

            using (var destinationStream = new InMemoryRandomAccessStream())
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);
                encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, decoder.PixelWidth,
                    decoder.PixelHeight, 96, 96, pixelData.DetachPixelData());
                await encoder.FlushAsync();

                BitmapDecoder outputDecoder = await BitmapDecoder.CreateAsync(destinationStream);
                await destinationStream.FlushAsync();
                imageArray = (await outputDecoder.GetPixelDataAsync()).DetachPixelData();
            }
            return imageArray;
        }
开发者ID:orangpelupa,项目名称:PlayStation-App,代码行数:27,代码来源:AttachImageCommand.cs

示例2: ConvertToInMemoryStream

 public static async Task<InMemoryRandomAccessStream> ConvertToInMemoryStream(byte[] arr)
 {
     var randomAccessStream = new InMemoryRandomAccessStream();
     await randomAccessStream.WriteAsync(arr.AsBuffer());
     randomAccessStream.Seek(0);
     await randomAccessStream.FlushAsync(); // TODO: don't sure it's needed
     return randomAccessStream;
 }
开发者ID:damonslu,项目名称:Charity,代码行数:8,代码来源:ConvertionExtensions.cs

示例3: SetSource

 public void SetSource(byte[] bytes)
 {
     var ms = new InMemoryRandomAccessStream();
     ms.WriteAsync(bytes.AsBuffer());
     ms.FlushAsync().AsTask().Wait();
     ms.Seek(0);
     bitmap = new BitmapImage();
     bitmap.SetSource(ms);
 }
开发者ID:hugoterelle,项目名称:mvvmcross-bitmap-plugin,代码行数:9,代码来源:MvxWindowsStoreBitmap.cs

示例4: SaveBitmapAsync

        public async Task SaveBitmapAsync(string albumFolder, uint size, string songPath)
        {
            var songFile = await StorageFile.GetFileFromPathAsync(songPath);

            using (var thumbnail = await songFile.GetThumbnailAsync(ThumbnailMode.MusicView, size) ??
                                   await songFile.GetThumbnailAsync(ThumbnailMode.VideosView, size))
            {
                if (thumbnail == null)
                    return;

                var reader = new DataReader(thumbnail);
                var fileLength = (uint)thumbnail.Size;
                await reader.LoadAsync(fileLength);

                var buffer = reader.ReadBuffer(fileLength);

                var memStream = new InMemoryRandomAccessStream();

                await memStream.WriteAsync(buffer);
                await memStream.FlushAsync();
                memStream.Seek(0);

                await ApplicationData.Current.LocalFolder.CreateFolderAsync(AlbumArtFolderName(albumFolder), CreationCollisionOption.OpenIfExists);

                var albumArtFileName = AlbumArtFileName(albumFolder, size);
                var outputFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(albumArtFileName, CreationCollisionOption.ReplaceExisting);

                // http://social.msdn.microsoft.com/Forums/windowsapps/en-US/1dda3a15-d299-40e0-b668-ec690a683f6e/how-to-resize-an-image-as-storagefile?forum=winappswithcsharp
                var decoder = await BitmapDecoder.CreateAsync(memStream);
                var transform = new BitmapTransform { ScaledHeight = size, ScaledWidth = size };
                var pixelData = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Straight,
                    transform,
                    ExifOrientationMode.RespectExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                using (var destinationStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);
                    encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, size, size, 96, 96, pixelData.DetachPixelData());
                    await encoder.FlushAsync();
                }
            }
        }
开发者ID:slewis74,项目名称:Jukebox,代码行数:45,代码来源:AlbumArtStorage.cs

示例5: DownloadAndScale

        private async void DownloadAndScale(string outfileName, string downloadUriString)
        {
             Uri downLoadingUri = new Uri(downloadUriString);
             var client = new HttpClient();
    
            using (var response = await client.GetAsync(downLoadingUri))
            {
                var buffer = await response.Content.ReadAsBufferAsync();
                var memoryStream = new InMemoryRandomAccessStream();
                await memoryStream.WriteAsync(buffer);
                await memoryStream.FlushAsync();
                var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(memoryStream);

                var pixelProvider = await decoder.GetPixelDataAsync();



                var localFolder = Windows.Storage.KnownFolders.PicturesLibrary;

                var scaledFile = await localFolder.CreateFileAsync(outfileName, CreationCollisionOption.GenerateUniqueName);
             
                using (var scaledFileStream = await scaledFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                {


                    var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync( BitmapEncoder.JpegEncoderId, scaledFileStream);
                    var pixels = pixelProvider.DetachPixelData();
                    encoder.SetPixelData(
                        decoder.BitmapPixelFormat,
                        decoder.BitmapAlphaMode,
                        decoder.PixelWidth,
                        decoder.PixelHeight,
                        decoder.DpiX,
                        decoder.DpiY,
                        pixels
                        );
                    await encoder.FlushAsync();
                }
            }
        }
开发者ID:x01673,项目名称:dreaming,代码行数:40,代码来源:ImageView.xaml.cs

示例6: UnprotectPDFStream

        public static async Task<IRandomAccessStream> UnprotectPDFStream(IRandomAccessStream source)
        {
            // Create a DataProtectionProvider object.
            DataProtectionProvider Provider = new DataProtectionProvider();

            InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream();
            IOutputStream dest = unprotectedData.GetOutputStreamAt(0);

            await Provider.UnprotectStreamAsync(source.GetInputStreamAt(0), dest);
            await unprotectedData.FlushAsync();
            unprotectedData.Seek(0);

            return unprotectedData;
        }
开发者ID:modulexcite,项目名称:windows8,代码行数:14,代码来源:DownloadManager.cs

示例7: DoImageProcessing

        private async void DoImageProcessing()
        {
            var ps = new InMemoryRandomAccessStream();

            while (processImage)
            {
                await capturePreview.Source.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), ps);
                await ps.FlushAsync();
                ps.Seek(0);

                WriteableBitmap bitmap = new WriteableBitmap(424, 240);
                bitmap.SetSource(ps);
                int bitmapSize = bitmap.PixelHeight * bitmap.PixelWidth * 4;

                using (Stream imageStream = bitmap.PixelBuffer.AsStream())
                {
                    byte[] bitmapPixelArray = new byte[bitmapSize];
                    await imageStream.ReadAsync(bitmapPixelArray, 0, bitmapSize);

                    for (int i = 0; i < bitmapSize; i += 4)
                    {
                        selectedPixelFunction(bitmapPixelArray, i);
                    }

                    imageStream.Seek(0, SeekOrigin.Begin);
                    await imageStream.WriteAsync(bitmapPixelArray, 0, bitmapSize);
                }
                imageProcess.Source = bitmap;
            }
            selectedPixelFunction = null;
        }
开发者ID:physicspackage,项目名称:WindowsStoreFastVideoProcessing,代码行数:31,代码来源:MainPage.xaml.cs

示例8: ConvertByteArrayToBitmapImage

        public static async Task<BitmapImage> ConvertByteArrayToBitmapImage(byte[] byteValue)
        {
            var img = new BitmapImage();

            var ras = new InMemoryRandomAccessStream();
            await ras.WriteAsync(byteValue.AsBuffer());
            await ras.FlushAsync();
            ras.Seek(0);
            img.SetSource(ras);

            return img;
        }
开发者ID:GeekyTheory,项目名称:GeekyTool,代码行数:12,代码来源:EncodeHelper.cs

示例9: GetCameraImage

        /// <summary>
        /// Perform image capture from mediaCapture object
        /// </summary>
        /// <param name="cancelToken">
        /// The cancel Token.
        /// </param>
        /// <returns>
        /// Decoded barcode string.
        /// </returns>
        private async Task<Result> GetCameraImage(CancellationToken cancelToken)
        {
            if (cancelToken.IsCancellationRequested)
            {
                throw new OperationCanceledException(cancelToken);
            }

            imageStream = new InMemoryRandomAccessStream();

            await capture.CapturePhotoToStreamAsync(encodingProps, imageStream);
            await imageStream.FlushAsync();

            var decoder = await BitmapDecoder.CreateAsync(imageStream);

            byte[] pixels = (await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8,
                BitmapAlphaMode.Ignore,
                new BitmapTransform(),
                ExifOrientationMode.IgnoreExifOrientation,
                ColorManagementMode.DoNotColorManage)).DetachPixelData();

            const BitmapFormat format = BitmapFormat.RGB32;

            imageStream.Dispose();

            var result =
                await
                    Task.Run(
                        () => barcodeReader.Decode(pixels, (int)decoder.PixelWidth, (int)decoder.PixelHeight, format),
                        cancelToken);

            return result;
        }
开发者ID:TomKaminski,项目名称:ItadMobileApp,代码行数:41,代码来源:Reader.cs

示例10: LoadImageFromHttpResponse

        private async Task<bool> LoadImageFromHttpResponse(HttpResponseMessage response, Tile tile, BitmapSource image, string cacheKey)
        {
            using (var stream = new InMemoryRandomAccessStream())
            {
                using (var content = response.Content)
                {
                    await content.WriteToStreamAsync(stream);
                }

                await stream.FlushAsync();
                stream.Seek(0);

                var loaded = await LoadImageFromStream(tile, image, stream);

                if (loaded && cacheKey != null)
                {
                    var buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);

                    stream.Seek(0);
                    await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);

                    var maxAge = DefaultCacheExpiration;

                    if (response.Headers.CacheControl.MaxAge.HasValue &&
                        response.Headers.CacheControl.MaxAge.Value < maxAge)
                    {
                        maxAge = response.Headers.CacheControl.MaxAge.Value;
                    }

                    await Cache.SetAsync(cacheKey, buffer, DateTime.UtcNow.Add(maxAge));
                }

                return loaded;
            }
        }
开发者ID:huoxudong125,项目名称:XamlMapControl,代码行数:35,代码来源:TileImageLoader.WinRT.cs

示例11: AnalyzeButton_Click

        private async void AnalyzeButton_Click(object sender, RoutedEventArgs e)
        {
            if (processingImage)
            {
                // Ignore button presses while processing the image
                return;
            }

            if (inCaptureState)
            {
                processingImage = true;
                inCaptureState = false;

                // Make the 'Processing...' label visible
                canvasControl.Visibility = Visibility.Visible;
                AnalyzeButton.Content = "...";

                canvasControl.Invalidate();

                var originalPhoto = new InMemoryRandomAccessStream();
                var reencodedPhoto = new InMemoryRandomAccessStream();
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), originalPhoto);
                await originalPhoto.FlushAsync();
                originalPhoto.Seek(0);

                captureElement.Visibility = Visibility.Collapsed;

                // Store the captured photo as a Win2D type for later use
                photoCanvasBitmap = await CanvasBitmap.LoadAsync(canvasControl, originalPhoto);

                // Send the photo to Project Oxford to detect the faces
                lastCapturedFaces = await faceServiceClient.DetectAsync(originalPhoto.AsStreamForRead(), true, true, true, false);

                // Force the canvasControl to be redrawn now that the photo is available
                canvasControl.Invalidate();

                processingImage = false;
                AnalyzeButton.Content = "Restart";
            }
            else
            {
                canvasControl.Visibility = Visibility.Collapsed;
                captureElement.Visibility = Visibility.Visible;
                AnalyzeButton.Content = "Capture Photo";

                photoCanvasBitmap = null;
                canvasControl.Invalidate();

                inCaptureState = true;
            }
        }
开发者ID:austinkinross,项目名称:age-gender-guesser,代码行数:51,代码来源:MainPage.xaml.cs

示例12: ResizeStreamAsync

        private async Task<IRandomAccessStream> ResizeStreamAsync(IRandomAccessStream stream, Size size, PhotoOrientation orientation)
        {
            var rotation = 0;

            switch (orientation)
            {
                case PhotoOrientation.Rotate180:
                    {
                        rotation = -180;
                    };
                    break;

                case PhotoOrientation.Rotate270:
                    {
                        rotation = -270;
                    };
                    break;

                case PhotoOrientation.Rotate90:
                    {
                        rotation = -90;
                    };
                    break;
            }

            using (var resizedStream = new InMemoryRandomAccessStream())
            {
                var buffer = new byte[stream.Size].AsBuffer();

                stream.Seek(0);

                await stream.ReadAsync(buffer, buffer.Length, InputStreamOptions.None);

                var resizeConfiguration = new AutoResizeConfiguration(
                    (uint)(size.Width * size.Height * 4 * 2), size,
                    new Size(0, 0), AutoResizeMode.Automatic, 0.7, ColorSpace.Yuv420);

                buffer = await JpegTools.AutoResizeAsync(buffer, resizeConfiguration);

                await resizedStream.WriteAsync(buffer);
                await resizedStream.FlushAsync();

                if (rotation != 0)
                {
                    resizedStream.Seek(0);

                    var filters = new List<IFilter>() { new RotationFilter(rotation) };

                    using (var source = new RandomAccessStreamImageSource(resizedStream))
                    using (var effect = new FilterEffect(source) { Filters = filters })
                    using (var renderer = new JpegRenderer(effect))
                    {
                        buffer = await renderer.RenderAsync();

                        using (var rotatedResizedStream = new InMemoryRandomAccessStream())
                        {
                            await rotatedResizedStream.WriteAsync(buffer);
                            await rotatedResizedStream.FlushAsync();

                            return rotatedResizedStream.CloneStream();
                        }
                    }
                }
                else
                {
                    return resizedStream.CloneStream();
                }
            }
        }
开发者ID:roachhd,项目名称:filter-explorer,代码行数:69,代码来源:PhotoModel.cs

示例13: generatePeerImage

        public override object generatePeerImage()
        {
            int width = getWidth();
            int height = getHeight();
            if (width <= 0 || height <= 0)
            {
                width = getPreferredW();
                height = getPreferredH();
            }
            CodenameOneImage img = new CodenameOneImage();
            [email protected]();
            img.name = "PeerImage: " + element.ToString();
            IRandomAccessStream stream = new InMemoryRandomAccessStream();
            CanvasBitmap cb = null;
            SilverlightImplementation.dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                if (element is WebView)
                {
                    await ((WebView)element).CapturePreviewToStreamAsync(stream);
                    await stream.FlushAsync();
                    stream.Seek(0);
                    cb = await CanvasBitmap.LoadAsync(SilverlightImplementation.screen, stream);
                }
                else
                {
                    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
                    await renderTargetBitmap.RenderAsync(element);
                    byte[] buf = renderTargetBitmap.GetPixelsAsync().AsTask().ConfigureAwait(false).GetAwaiter().GetResult().ToArray();
                    cb = CanvasBitmap.CreateFromBytes(SilverlightImplementation.screen, buf, width, height,
                    SilverlightImplementation.pixelFormat, SilverlightImplementation.screen.Dpi);
                }
                img.image = new CanvasRenderTarget(SilverlightImplementation.screen, cb.SizeInPixels.Width, cb.SizeInPixels.Height, cb.Dpi);
                img.graphics.destination.drawImage(cb, 0, 0);
                img.graphics.destination.dispose();

            }).AsTask().GetAwaiter().GetResult();
            return ui.Image.createImage(img);
        }
开发者ID:Pmovil,项目名称:CN1WindowsPort,代码行数:38,代码来源:SilverlightPeer.cs

示例14: DownloadPDFAsync

        public async Task<IRandomAccessStream> DownloadPDFAsync(LibrelioLocalUrl magUrl, StorageFolder folder, IProgress<int> progress = null, CancellationToken cancelToken = default(CancellationToken))
        {
            HttpClient client = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, magUrl.Url);

            int read = 0;
            int offset = 0;
            byte[] responseBuffer = new byte[1024];

            var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancelToken);
            response.EnsureSuccessStatusCode();

            var length = response.Content.Headers.ContentLength;

            cancelToken.ThrowIfCancellationRequested();

            var stream = new InMemoryRandomAccessStream();

            using (var responseStream = await response.Content.ReadAsStreamAsync())
            {
                do
                {
                    cancelToken.ThrowIfCancellationRequested();

                    read = await responseStream.ReadAsync(responseBuffer, 0, responseBuffer.Length);

                    cancelToken.ThrowIfCancellationRequested();

                    await stream.AsStream().WriteAsync(responseBuffer, 0, read);

                    offset += read;
                    uint val = (uint)(offset * 100 / length);
                    if (val >= 100) val = 99;
                    if (val <= 0) val = 1;
                    progress.Report((int)val);
                }
                while (read != 0);
            }

            progress.Report(100);

            await stream.FlushAsync();

            //var folder = await AddMagazineFolderStructure(magUrl);
            //var folder = await StorageFolder.GetFolderFromPathAsync(folderUrl);
            var file = await folder.CreateFileAsync(magUrl.FullName, CreationCollisionOption.ReplaceExisting);

            using (var protectedStream = await DownloadManager.ProtectPDFStream(stream))
            using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
            //using (var unprotectedStream = await DownloadManager.UnprotectPDFStream(protectedStream))
            {

                await RandomAccessStream.CopyAsync(protectedStream, fileStream.GetOutputStreamAt(0));

                await fileStream.FlushAsync();
            }
            var pdfStream = new MagazineData();
            pdfStream.folderUrl = folder.Path + "\\";
            pdfStream.stream = stream;
            //var fileHandle =
            //    await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\test\testmagazine.pdf");

            //pdfStream.folderUrl = "C:\\Users\\Dorin\\Documents\\Magazines\\wind_355\\";
            //pdfStream.stream = await fileHandle.OpenReadAsync();

            return pdfStream.stream;
        }
开发者ID:umairsheikh,项目名称:windows8,代码行数:68,代码来源:MagazineManager.cs

示例15: generatePeerImage

        public override object generatePeerImage()
        {
            int width = getWidth();
            int height = getHeight();
            if (width <= 0 || height <= 0)
            {
                width = getPreferredW();
                height = getPreferredH();
            }
            if (element.Parent == null)
            {
                if (peerImage != null)
                {
                    return peerImage;
                }
                return com.codename1.ui.Image.createImage(width, height);
            }
            CodenameOneImage img = new CodenameOneImage();
            [email protected]();
            img.name = "PeerImage: " + element.ToString();
            IRandomAccessStream stream = new InMemoryRandomAccessStream();
            CanvasBitmap cb = null;
            using (AutoResetEvent are = new AutoResetEvent(false))
            {
                SilverlightImplementation.dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
              {
                  if (element is WebView)
                  {
                      try
                      {
                          Task.Delay(TimeSpan.FromTicks(4).Duration()).GetAwaiter().GetResult();
                          ((WebView)element).CapturePreviewToStreamAsync(stream).AsTask().GetAwaiter().GetResult();
                          stream.FlushAsync().AsTask().GetAwaiter().GetResult();
                          stream.Seek(0);
                          Task.Delay(TimeSpan.FromMilliseconds(10)).GetAwaiter().GetResult();
                          cb = CanvasBitmap.LoadAsync(SilverlightImplementation.screen, stream).AsTask().GetAwaiter().GetResult();
                      }
                      catch (Exception)
                      {

                          throw;
                      }

                  }
                  else
                  {
                      RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
                      renderTargetBitmap.RenderAsync(element).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
                      byte[] buf = renderTargetBitmap.GetPixelsAsync().AsTask().ConfigureAwait(false).GetAwaiter().GetResult().ToArray();
                      cb = CanvasBitmap.CreateFromBytes(SilverlightImplementation.screen, buf, width, height, SilverlightImplementation.pixelFormat, SilverlightImplementation.screen.Dpi);
                  }
                  img.image = new CanvasRenderTarget(SilverlightImplementation.screen, cb.SizeInPixels.Width, cb.SizeInPixels.Height, cb.Dpi);
                  img.graphics.destination.drawImage(cb, 0, 0);
                  img.graphics.destination.dispose();
                  are.Set();
              }).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
                are.WaitOne();
            }
            return com.codename1.ui.Image.createImage(img);

            // return com.codename1.ui.Image.createImage(width, height);
        }
开发者ID:shannah,项目名称:CN1WindowsPort,代码行数:62,代码来源:SilverlightImplementation_2.cs


注:本文中的Windows.Storage.Streams.InMemoryRandomAccessStream.FlushAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。