當前位置: 首頁>>代碼示例>>C#>>正文


C# InMemoryRandomAccessStream.AsStream方法代碼示例

本文整理匯總了C#中Windows.Storage.Streams.InMemoryRandomAccessStream.AsStream方法的典型用法代碼示例。如果您正苦於以下問題:C# InMemoryRandomAccessStream.AsStream方法的具體用法?C# InMemoryRandomAccessStream.AsStream怎麽用?C# InMemoryRandomAccessStream.AsStream使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Windows.Storage.Streams.InMemoryRandomAccessStream的用法示例。


在下文中一共展示了InMemoryRandomAccessStream.AsStream方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: SaveResultToCameraRollAsync

        /// <summary>
        /// Asynchronously saves the <paramref name="photo" /> given to the camera roll album.
        /// </summary>
        /// <param name="photo">Photo to save.</param>
        /// <returns>Image with thumbnail.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="photo"/> is <see langword="null"/>.</exception>
        public async Task<IThumbnailedImage> SaveResultToCameraRollAsync(ICapturedPhoto photo)
        {
            if (photo == null)
            {
                throw new ArgumentNullException("photo");
            }

            Tracing.Trace("StorageService: Trying to save picture to the Camera Roll.");

            Picture cameraRollPicture;
            string name = this.GeneratePhotoName();

            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                // Convert image to JPEG format and rotate in accordance with the original photo orientation.
                Tracing.Trace("StorageService: Converting photo to JPEG format. Size: {0}x{1}, Rotation: {2}", photo.Width, photo.Height, photo.Rotation);
                byte[] pixelData = await photo.DetachPixelDataAsync();

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
                encoder.BitmapTransform.Rotation = photo.Rotation;
                encoder.BitmapTransform.Flip     = photo.Flip;
                encoder.IsThumbnailGenerated     = true;

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, photo.Width, photo.Height, Constants.DefaultDpiX, Constants.DefaultDpiY, pixelData);
                await encoder.FlushAsync();

                cameraRollPicture = this.lazyMediaLibrary.Value.SavePictureToCameraRoll(name, stream.AsStream());
            }

            Tracing.Trace("StorageService: Saved to Camera Roll as {0}", name);

            return new MediaLibraryThumbnailedImage(cameraRollPicture);
        }
開發者ID:trilok567,項目名稱:Windows-Phone,代碼行數:39,代碼來源:StorageService.cs

示例2: FromStream

		internal static Bitmap FromStream(Stream stream)
		{
		    Bitmap bitmap = null;

		    Task.Run(async () =>
		    {
		        using (var raStream = new InMemoryRandomAccessStream())
		        {
		            await stream.CopyToAsync(raStream.AsStream());
		            var decoder = await BitmapDecoder.CreateAsync(raStream);
		            var pixelData = await decoder.GetPixelDataAsync();

		            var width = (int)decoder.OrientedPixelWidth;
		            var height = (int)decoder.OrientedPixelHeight;
		            const PixelFormat format = PixelFormat.Format32bppArgb;
		            var bytes = pixelData.DetachPixelData();

                    bitmap = new Bitmap(width, height, format);
                    var data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, format);
                    Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);
                    bitmap.UnlockBits(data);
                }
		    }).Wait();

		    return bitmap;
		}
開發者ID:hungdluit,項目名稱:aforge,代碼行數:26,代碼來源:Bitmap.Store.cs

示例3: manager_DataRequested

        void manager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            // do the basics...
            var data = args.Request.Data;
            data.Properties.Title = "Deferred image";
            data.Properties.Description = "I'll have to be downloaded first!";

            // get a deferral...
            data.SetDataProvider(StandardDataFormats.Bitmap, async (request) => 
            {
                var deferral = request.GetDeferral();
                try
                {
                    // download...
                    using (var inStream = await new HttpClient().GetStreamAsync("http://streetfoo.apphb.com/images/graffiti00.jpg"))
                    {
                        // copy the stream... but we'll need to obtain a facade
                        // to map between WinRT and .NET...
                        var outStream = new InMemoryRandomAccessStream();
                        inStream.CopyTo(outStream.AsStream());

                        // send that...
                        var reference = RandomAccessStreamReference.CreateFromStream(outStream);
                        request.SetData(reference);
                    }
                }
                finally
                {
                    deferral.Complete();
                }

            });
        }
開發者ID:jimgrant,項目名稱:ProgrammingWindowsStoreApps,代碼行數:33,代碼來源:MainPage.xaml.cs

示例4: AsRandomAccessStream

 public static IRandomAccessStream AsRandomAccessStream(this Stream stream)
 {
     // This is bad, as we are reading the whole input stream in memory, but better than nothing.
     var randomStream = new InMemoryRandomAccessStream();
     stream.CopyTo(randomStream.AsStream());
     randomStream.Seek(0);
     return randomStream;
 }
開發者ID:Nezz,項目名稱:SharpDX,代碼行數:8,代碼來源:RandomStream.cs

示例5: Run

        private async void Run()
        {
            await _HubConnection.Start();

            var cam = new MediaCapture();

            await cam.InitializeAsync(new MediaCaptureInitializationSettings()
            {
                MediaCategory = MediaCategory.Media,
                StreamingCaptureMode = StreamingCaptureMode.Video
            });

            _Sensor.MotionDetected += async (int pinNum) =>
            {
                var stream = new InMemoryRandomAccessStream();
                Stream imageStream = null;
                try
                {
                    await Task.Factory.StartNew(async () =>
                    {
                        _Sensor.IsActive = false;
                        await cam.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
                        stream.Seek(0);
                        imageStream = stream.AsStream();
                        imageStream.Seek(0, SeekOrigin.Begin);
                        string imageUrl = await NotificationHelper.UploadImageAsync(imageStream);

                        switch (await OxfordHelper.IdentifyAsync(imageUrl))
                        {
                            case AuthenticationResult.IsOwner:
                                // open the door
                                MotorController.PWM(26);
                                break;

                            case AuthenticationResult.Unkown:
                                // send notification to the owner
                                NotificationHelper.NotifyOwnerAsync(imageUrl);
                                break;

                            case AuthenticationResult.None:
                            default:
                                break;
                        }
                        _Sensor.IsActive = true;
                    });
                }
                finally
                {
                    if (stream != null)
                        stream.Dispose();
                    if (imageStream != null)
                        imageStream.Dispose();
                }
            };
        }
開發者ID:BertusV,項目名稱:Home-Visits-Manager,代碼行數:55,代碼來源:VisitorsController.cs

示例6: EncodeFromByte

        public static async Task<string> EncodeFromByte(byte[] image, uint height, uint width, double dpiX = 96, double dpiY = 96)
        {
            // encode image
            var encoded = new InMemoryRandomAccessStream();
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, encoded);
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, height, width, dpiX, dpiY, image);
            await encoder.FlushAsync();
            encoded.Seek(0);

            // read bytes
            var bytes = new byte[encoded.Size];
            await encoded.AsStream().ReadAsync(bytes, 0, bytes.Length);

            // create base64
            return Convert.ToBase64String(bytes);
        }
開發者ID:Lukasss93,項目名稱:AuraRT,代碼行數:16,代碼來源:Base64.cs

示例7: ScaleImageStreamAsync

        /// <summary>
        /// Scales the image in the given memory stream.
        /// </summary>
        /// <param name="originalStream">The original image stream to scale.</param>
        /// <param name="originalResolutionWidth">The original width.</param>
        /// <param name="originalResolutionHeight">The original height.</param>
        /// <param name="scaledStream">Stream where the scaled image is stored.</param>
        /// <param name="scaleWidth">The target width.</param>
        /// <param name="scaleHeight">The target height.</param>
        /// <returns></returns>
        public static async Task ScaleImageStreamAsync(MemoryStream originalStream,
                                                       int originalResolutionWidth,
                                                       int originalResolutionHeight,
                                                       MemoryStream scaledStream,
                                                       int scaleWidth,
                                                       int scaleHeight)
        {
            System.Diagnostics.Debug.WriteLine(DebugTag + "ScaleImageStreamAsync() ->");

            // Create a bitmap containing the full resolution image
            var bitmap = new WriteableBitmap(originalResolutionWidth, originalResolutionHeight);
            originalStream.Seek(0, SeekOrigin.Begin);
            await bitmap.SetSourceAsync(originalStream.AsRandomAccessStream());

            /* Construct a JPEG encoder with the newly created
             * InMemoryRandomAccessStream as target
             */
            IRandomAccessStream previewResolutionStream = new InMemoryRandomAccessStream();
            previewResolutionStream.Size = 0;
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(
                BitmapEncoder.JpegEncoderId, previewResolutionStream);

            // Copy the full resolution image data into a byte array
            Stream pixelStream = bitmap.PixelBuffer.AsStream();
            var pixelArray = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixelArray, 0, pixelArray.Length);

            // Set the scaling properties
            encoder.BitmapTransform.ScaledWidth = (uint)scaleWidth;
            encoder.BitmapTransform.ScaledHeight = (uint)scaleHeight;
            encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
            encoder.IsThumbnailGenerated = true;

            // Set the image data and the image format setttings to the encoder
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                (uint)originalResolutionWidth, (uint)originalResolutionHeight,
                96.0, 96.0, pixelArray);

            await encoder.FlushAsync();
            previewResolutionStream.Seek(0);
            await previewResolutionStream.AsStream().CopyToAsync(scaledStream);

            System.Diagnostics.Debug.WriteLine(DebugTag + "<- ScaleImageStreamAsync()");
        }
開發者ID:TheHypnotoad,項目名稱:filter-effects,代碼行數:54,代碼來源:AppUtils.cs

示例8: ResizeImage

        public async Task<PortableImage> ResizeImage(PortableImage image, int newWidth, int newHeight)
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(((Stream)image.EncodedData).AsRandomAccessStream());

            var memoryRandomAccessStream = new InMemoryRandomAccessStream();
            BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memoryRandomAccessStream, decoder);

            encoder.BitmapTransform.ScaledHeight = (uint)newHeight;
            encoder.BitmapTransform.ScaledWidth = (uint)newWidth;


            //var bounds = new BitmapBounds();
            //bounds.Height = 50;
            //bounds.Width = 50;
            //bounds.X = 50;
            //bounds.Y = 50;
            //enc.BitmapTransform.Bounds = bounds;

            try
            {
                await encoder.FlushAsync();
            }
            catch (Exception exc)
            {
                var message = "Error on resizing the image: ";

                if (exc.Message != null)
                    message += exc.Message;

                throw new Exception(message);
            }

            //var writeableBitmap = new WriteableBitmap(newWidth, newHeight);
            //writeableBitmap.SetSourceAsync(memoryRandomAccessStream);

            memoryRandomAccessStream.Seek(0);

            return new PortableImage
            {
                Width = newWidth,
                Height = newHeight,
                EncodedData = memoryRandomAccessStream.AsStream()
            };
        }
開發者ID:Catrobat,項目名稱:CatrobatForWindows,代碼行數:44,代碼來源:ImageResizeServiceWindowsShared.cs

示例9: play

 private void play(double note)
 {
     MediaElement playback = new MediaElement();
     IRandomAccessStream stream = new InMemoryRandomAccessStream();
     BinaryWriter writer = new BinaryWriter(stream.AsStream());
     int formatChunkSize = 16;
     int headerSize = 8;
     short formatType = 1;
     short tracks = 1;
     int samplesPerSecond = 44100;
     short bitsPerSample = 16;
     short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8));
     int bytesPerSecond = samplesPerSecond * frameSize;
     int waveSize = 4;
     int data = 0x61746164;
     int samples = 88200 * 4;
     int dataChunkSize = samples * frameSize;
     int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize;
     double frequency = note * 1.5;
     writer.Write(0x46464952); // RIFF
     writer.Write(fileSize);
     writer.Write(0x45564157); // WAVE
     writer.Write(0x20746D66); // Format
     writer.Write(formatChunkSize);
     writer.Write(formatType);
     writer.Write(tracks);
     writer.Write(samplesPerSecond);
     writer.Write(bytesPerSecond);
     writer.Write(frameSize);
     writer.Write(bitsPerSample);
     writer.Write(data);
     writer.Write(dataChunkSize);
     for (int i = 0; i < samples / 4; i++)
     {
         double t = (double)i / (double)samplesPerSecond;
         short s = (short)(10000 * (Math.Sin(t * frequency * 2.0 * Math.PI)));
         writer.Write(s);
     }
     stream.Seek(0);
     playback.SetSource(stream, "audio/wav");
     playback.Play();
 }
開發者ID:RoguePlanetoid,項目名稱:Windows-10-Universal-Windows-Platform,代碼行數:42,代碼來源:Library.cs

示例10: btnTakePhoto_Click

        private async void btnTakePhoto_Click(object sender, RoutedEventArgs e)
        {
            btnTakePhoto.IsEnabled = false;
            btnStartPreview.IsEnabled = false;

            InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
            await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

            stream.Seek(0);
            BitmapImage bitmap = new BitmapImage();
            bitmap.SetSource(stream);
            captureImage.Source = bitmap;

            stream.Seek(0);
            Stream st = stream.AsStream();

            if (isPreviewing == true) await mediaCapture.StopPreviewAsync();
            isPreviewing = false;
            previewElement.Visibility = Visibility.Collapsed;

            progring.IsActive = true;

                try
                {
                    EmotionServiceClient emotionServiceClient =
                            new EmotionServiceClient("12345678901234567890123456789012");
        // replace 12345678901234567890123456789012 with your key taken from https://www.projectoxford.ai/Subscription/
                    emotionResult = await emotionServiceClient.RecognizeAsync(st);
                }
                catch { }

            progring.IsActive = false;

            if ((emotionResult != null) && (emotionResult.Length > 0))
            {
                emo.Clear();
                emo.Add(emotionResult[0]);
                this.DataContext = emo.ElementAt(0);
            }
            btnStartPreview.IsEnabled = true;
            btnTakePhoto.IsEnabled = true;
        }
開發者ID:hoai,項目名稱:Project_Oxford_Emotions_UWP,代碼行數:42,代碼來源:MainPage.xaml.cs

示例11: DetectPhotoAsync

        private async Task DetectPhotoAsync(IRandomAccessStream stream, PhotoOrientation photoOrientation)
        {
            using (var inputStream = stream)
            {
                var decoder = await BitmapDecoder.CreateAsync(inputStream);

                var file = await KnownFolders.PicturesLibrary.CreateFileAsync("SimplePhoto.jpeg", CreationCollisionOption.GenerateUniqueName);

                using (var outputStream = new InMemoryRandomAccessStream())
                {
                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

                    var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };

                    await encoder.BitmapProperties.SetPropertiesAsync(properties);
                    await encoder.FlushAsync();

                    var faces = await _instance.DetectAsync(outputStream.AsStream(), false, true, true, false);
                }
            }
        }
開發者ID:Alex-Witkowski,項目名稱:PersonalMirror,代碼行數:21,代碼來源:MainPage.xaml.cs

示例12: StartRecordingToStreamAsync

        /// <summary>
        /// Start recording a new video and save it as stream.
        /// </summary>
        /// <param name="encoding">The video encoding. Mp4 by default.</param>
        /// <returns>The <see cref="VideoCaptureStreamResult"/> struct.</returns>
        public async Task<VideoCaptureStreamResult> StartRecordingToStreamAsync(VideoEncoding encoding)
        {
            if (!this.isInitialized)
            {
                Debug.WriteLine("First you need to initialize the videocapturemanager.");
                return new VideoCaptureStreamResult();
            }

            if (this.IsRecording)
            {
                Debug.WriteLine("VideoCapture is already recording. Call Stop before Start again.");
                return new VideoCaptureStreamResult(false, Stream.Null);
            }

            try
            {
                Debug.WriteLine("Recording video...");
                MediaEncodingProfile encodingProfile;

                switch (encoding)
                {
                    case VideoEncoding.AVI:
                        encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
                        break;
                    case VideoEncoding.WMV:
                        encodingProfile = MediaEncodingProfile.CreateWmv(VideoEncodingQuality.Auto);
                        break;
                    default:
                    case VideoEncoding.MP4:
                        encodingProfile = MediaEncodingProfile.CreateAvi(VideoEncodingQuality.Auto);
                        break;
                }

                var stream = new InMemoryRandomAccessStream();
                await this.mediaCapture.StartRecordToStreamAsync(encodingProfile, stream);
                this.isRecording = true;

                return new VideoCaptureStreamResult(true, stream.AsStream());
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception when recording a video: " + ex.ToString());
                return new VideoCaptureStreamResult(false, Stream.Null);
            }
        }
開發者ID:WaveEngine,項目名稱:Extensions,代碼行數:50,代碼來源:VideoCaptureManager.cs

示例13: TakePhotoToStreamAsync

        /// <summary>
        /// Take a new photo and hold it in the output stream.
        /// </summary>
        /// <param name="parameters">The set of parameters used to take the photo, <see cref="ICameraResolution"/> class.</param>
        /// <param name="format">The image format. <see cref="PhotoCaptureFormat"/> enum. </param>
        /// <returns>The <see cref="PhotoCaptureStreamResult"/> struct.</returns>
        public async Task<PhotoCaptureStreamResult> TakePhotoToStreamAsync(ICameraResolution parameters, PhotoCaptureFormat format)
        {
            if (!this.isInitialized)
            {
                Debug.WriteLine("First you need to initialize the videocapturemanager.");
                return new PhotoCaptureStreamResult();
            }

            try
            {
                if (parameters != null)
                {
                    Debug.WriteLine("Applying paramenters...");
                    await this.mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, (parameters as StreamResolution).EncodingProperties);
                }

                Debug.WriteLine("Taking photo...");
                var stream = new InMemoryRandomAccessStream();

                var properties = this.GetImageEncodingProperties(format);
                await this.mediaCapture.CapturePhotoToStreamAsync(properties, stream);

                Debug.WriteLine("Photo stream loaded.");
                return new PhotoCaptureStreamResult(true, stream.AsStream());
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
                return new PhotoCaptureStreamResult(false, Stream.Null);
            }
        }
開發者ID:WaveEngine,項目名稱:Extensions,代碼行數:37,代碼來源:VideoCaptureManager.cs

示例14: ResizeImage

        /// <summary>
        /// resizes the image so it can go through VMHub processing
        /// </summary>
        /// <param name="ms"></param>
        /// <param name="maxImageSize"></param>
        /// <returns></returns>
        async private Task<byte[]> ResizeImage(MemoryStream ms, uint maxImageSize)
        {
            MemoryStream temp = ms;
            IRandomAccessStream ras = temp.AsRandomAccessStream();
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ras).AsTask().ConfigureAwait(false);

            uint w = decoder.PixelWidth, h = decoder.PixelHeight;
            if (w > maxImageSize || h > maxImageSize)
            {
                if (w > h)
                {
                    w = maxImageSize;
                    h = decoder.PixelHeight * maxImageSize / decoder.PixelWidth;
                }
                else
                {
                    w = decoder.PixelWidth * maxImageSize / decoder.PixelHeight;
                    h = maxImageSize;
                }
            }
            BitmapTransform transform = new BitmapTransform() { ScaledHeight = h, ScaledWidth = w };
            PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Rgba8,
                BitmapAlphaMode.Premultiplied,
                transform,
                ExifOrientationMode.RespectExifOrientation,
                ColorManagementMode.DoNotColorManage);

            byte[] pixels = pixelData.DetachPixelData();

            InMemoryRandomAccessStream encoded = new InMemoryRandomAccessStream();
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, encoded);
            encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, w, h, 96, 96, pixels);
            await encoder.FlushAsync().AsTask().ConfigureAwait(false);
            encoded.Seek(0);
            byte[] outBytes = new byte[encoded.Size];
            await encoded.AsStream().ReadAsync(outBytes, 0, outBytes.Length);
            return outBytes;
        }
開發者ID:MSRCCS,項目名稱:AppSuite,代碼行數:45,代碼來源:OptionsProxy.xaml.cs

示例15: RenderToBase64

        public async Task<string> RenderToBase64(UIElement element)
        {
            RenderTargetBitmap rtb = new RenderTargetBitmap();
            await rtb.RenderAsync(element);

            var pixelBuffer = await rtb.GetPixelsAsync();
            var pixels = pixelBuffer.ToArray();

            // Useful for rendering in the correct DPI
            var displayInformation = DisplayInformation.GetForCurrentView();

            var stream = new InMemoryRandomAccessStream();
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
            encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                 BitmapAlphaMode.Premultiplied,
                                 (uint)rtb.PixelWidth,
                                 (uint)rtb.PixelHeight,
                                 displayInformation.RawDpiX,
                                 displayInformation.RawDpiY,
                                 pixels);

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

            // read bytes
            var bytes = new byte[stream.Size];
            await stream.AsStream().ReadAsync(bytes, 0, bytes.Length);

            // create base64
            return Convert.ToBase64String(bytes);
        }
開發者ID:dachibox,項目名稱:UWP-Samples,代碼行數:31,代碼來源:MainViewModel.cs


注:本文中的Windows.Storage.Streams.InMemoryRandomAccessStream.AsStream方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。