Example #1
0
        public async Task<SoftwareBitmapSource> ConvertToSoftwareBitmapSource(SoftwareBitmap bitmap)
        {
            SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource();
            await bitmapSource.SetBitmapAsync(bitmap);

            return bitmapSource;
        }
Example #2
0
            public static Windows.Graphics.Imaging.SoftwareBitmap FromSoftwareBitmap(Windows.Graphics.Imaging.SoftwareBitmap bitmap)
            {
                var copy = new Windows.Graphics.Imaging.SoftwareBitmap(bitmap.BitmapPixelFormat, bitmap.PixelWidth, bitmap.PixelHeight);

                bitmap.CopyTo(copy);
                return(copy);
            }
Example #3
0
            public static Windows.Graphics.Imaging.SoftwareBitmap FromImage(Image <byte> image, int?width = null, int?height = null)
            {
                var bitmap = new Windows.Graphics.Imaging.SoftwareBitmap(BitmapPixelFormat.Unknown, width ?? image.Width, width ?? image.Height);

                bitmap.CopyFromBuffer(image.Pixels.AsBuffer());
                return(bitmap);
            }
Example #4
0
            public static Image <byte> FromSoftwareBitmap(Windows.Graphics.Imaging.SoftwareBitmap bitmap)
            {
                var bytes = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4];

                bitmap.CopyToBuffer(bytes.AsBuffer());
                return(new Image <byte>(bytes, bitmap.PixelWidth, bitmap.PixelHeight, 4, bitmap.PixelWidth * 4, false));
            }
        private unsafe void CalculateLuminance(SoftwareBitmap bitmap)
        {
            // Effect is hard-coded to operate on BGRA8 format only
            if (bitmap.BitmapPixelFormat == BitmapPixelFormat.Bgra8)
            {
                // In BGRA8 format, each pixel is defined by 4 bytes
                const int BYTES_PER_PIXEL = 4;

                using (var buffer = bitmap.LockBuffer(BitmapBufferAccessMode.Read))
                using (var reference = buffer.CreateReference())
                {

                    if (reference is IMemoryBufferByteAccess)
                    {


                        try
                        {
                            // Get a pointer to the pixel buffer
                            byte* data;
                            uint capacity;
                            ((IMemoryBufferByteAccess)reference).GetBuffer(out data, out capacity);

                            // Get information about the BitmapBuffer
                            var desc = buffer.GetPlaneDescription(0);
                            var luminanceIndex = 0;

                            // Iterate over all pixels
                            for (uint row = 0; row < desc.Height; row++)
                            {
                                for (uint col = 0; col < desc.Width; col++)
                                {
                                    // Index of the current pixel in the buffer (defined by the next 4 bytes, BGRA8)
                                    var currPixel = desc.StartIndex + desc.Stride * row + BYTES_PER_PIXEL * col;

                                    // Read the current pixel information into b,g,r channels (leave out alpha channel)
                                    var b = data[currPixel + 0]; // Blue
                                    var g = data[currPixel + 1]; // Green
                                    var r = data[currPixel + 2]; // Red

                                    var luminance = (byte)((RChannelWeight * r + GChannelWeight * g + BChannelWeight * b) >> ChannelWeight);
                                    var alpha = data[currPixel + 3];
                                    luminance = (byte)(((luminance * alpha) >> 8) + (255 * (255 - alpha) >> 8));
                                    luminances[luminanceIndex] = luminance;
                                    luminanceIndex++;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine("Luminance Source Failed: {0}", ex);
                        }
                    }
                }
            }
        }
		public RenderResult(SoftwareBitmap softwareBitmap, Size size, long setupTimeMillis, long renderTimeMillis)
		{
			SoftwareBitmap = softwareBitmap;
			Bitmap = null;
			Buffer = null;
			SwapChainPanel = null;
			Size = size;
			SetupTimeMillis = setupTimeMillis;
			RenderTimeMillis = renderTimeMillis;
		}
Example #7
0
        private async void OnFoo(object sender, RoutedEventArgs e)
        {
            using (var bitmap = await this.CaptureVisualAsync())
            {
                await bitmap.LogAsync("Test");
            }

            Size bmpSize = this.RenderSize;

            Windows.Graphics.Imaging.SoftwareBitmap swBmp = new Windows.Graphics.Imaging.SoftwareBitmap(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, ((int)bmpSize.Width), ((int)bmpSize.Height), Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied);

            var renderTgtBmp = new RenderTargetBitmap();
            await renderTgtBmp.RenderAsync(this);

            await SaveBitmap(renderTgtBmp, swBmp);
        }
Example #8
0
        private async void BrowsePhotoButton_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");

            StorageFile file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                photoStream = await camera.ConvertToStream(file);
                photoBitmap = await camera.ConvertToSoftwareBitmap(photoStream);
                photoBitmapSource = await camera.ConvertToSoftwareBitmapSource(photoBitmap);
            }
        }
        private async void OnPageLoaded(object sender, RoutedEventArgs e)
        {
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;

            var file = await StorageFile.GetFileFromApplicationUriAsync(new System.Uri("ms-appx:///Assets/defaultImage.jpg"));

            var storageFileImageSource = new StorageFileImageSource(file);
            var asyncImageResource = storageFileImageSource as IAsyncImageResource;
            var imageResource = await asyncImageResource.LoadAsync();
            m_imageSize = imageResource.ImageSize;
            var sepiaEffect = new Lumia.Imaging.Artistic.SepiaEffect(storageFileImageSource);

            SoftwareBitmapRenderer softwareBitmapRenderer = new SoftwareBitmapRenderer(sepiaEffect);

            m_sepiaEffectSoftwareBitmap = await softwareBitmapRenderer.RenderAsync();

            m_canvasControl.Invalidate();
        }
		public Task RenderAsync(SoftwareBitmap sourceBitmap, IImageProcessor processor)
        {
			var sourceBitmapSize = new Size(sourceBitmap.PixelWidth, sourceBitmap.PixelHeight);

			Debug.WriteLine(string.Format("RenderThumbnailAsync {0} sourceSize = {1} thumbnailSize = {2}", processor.Name, sourceBitmapSize, m_thumbnailSize));

            var effect = processor.GetEffectAsync(new SoftwareBitmapImageSource(sourceBitmap), sourceBitmapSize, m_thumbnailSize);

            // Avoid creating a Task object on the heap if not necessary.
            if (effect.IsSynchronous)
            {
                return FinishRenderAsync(effect.Result, processor);
            }
            else
            {
                return effect.Task.ContinueWith(effectTask => FinishRenderAsync(effectTask.Result, processor), TaskContinuationOptions.OnlyOnRanToCompletion);
            }
        }
    public async Task<Rect?> ProcessCameraFrameAsync(SoftwareBitmap bitmap)
    {
      if (this.faceDetector == null)
      {
        this.faceDetector = await FaceDetector.CreateAsync();
      }
      var result = await this.faceDetector.DetectFacesAsync(bitmap);

      this.photoControl.Switch(result?.Count > 0);

      Rect? returnValue = null;

      if (result?.Count > 0)
      {
        returnValue = new Rect(
          (double)result[0].FaceBox.X / bitmap.PixelWidth,
          (double)result[0].FaceBox.Y / bitmap.PixelHeight,
          (double)result[0].FaceBox.Width / bitmap.PixelWidth,
          (double)result[0].FaceBox.Height / bitmap.PixelHeight);
      }
      return (returnValue);
    }
Example #12
0
    private async Task <byte[]> EncodedBytes(Windows.Graphics.Imaging.SoftwareBitmap soft, Guid encoderId)
    {
        byte[] array = null;

        // First: Use an encoder to copy from SoftwareBitmap to an in-mem stream (FlushAsync)
        // Next:  Use ReadAsync on the in-mem stream to get byte[] array

        using (var ms = new InMemoryRandomAccessStream())
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, ms);

            encoder.SetSoftwareBitmap(soft);

            try
            {
                await encoder.FlushAsync();
            }
            catch (Exception ex) { return(new byte[0]); }

            array = new byte[ms.Size];
            await ms.ReadAsync(array.AsBuffer(), (uint)ms.Size, InputStreamOptions.None);
        }
        return(array);
    }
Example #13
0
        public void ProcessFrame(ProcessVideoFrameContext context)
        {
            if (context.InputFrame.SoftwareBitmap == null)
                return;

            var softwarebitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, context.InputFrame.SoftwareBitmap.PixelWidth, context.InputFrame.SoftwareBitmap.PixelHeight, context.OutputFrame.SoftwareBitmap.BitmapAlphaMode);
            context.InputFrame.SoftwareBitmap.CopyTo(softwarebitmap);

            recognizer.Treshold = (double)_configuration["tolerance"];
            recognizer.Hue = (int)_configuration["hue"];

            var result = recognizer.Recognize(softwarebitmap);
            var s = string.Empty;
            if (result != null)
            {
                for (int i = 0; i < result.GetLength(0); i++)
                {
                    for (int j = 0; j < result.GetLength(1); j++)
                    {
                        var t = result[i, j];
                        s += t == 0 ? " 0" : t.ToString();
                        s += ' ';
                    }
                    s += Environment.NewLine;
                }
            }

            if (result != null)
            {
                prevCount = 0;
                var matrix = new int[10, 10]
            {
                {   0,  0, -1,  0,  0,  0,  0, -1,  0,  0 },
                {   0,  0, -1,  0,  0,  0,  0, -1,  0,  0 },
                {  -1, -1, -1,  0,  0, -1,  0, -1,  0,  0 },
                {   0,  0, -1,  0, -1, -1, -1, -1, -1, -1 },
                {   0,  0, -1,  0,  0, -1,  0, -1,  0,  0 },
                {   0,  0, -1,  0,  0, -1,  0, -1,  0,  0 },
                {   0,  0, -1,  0,  0, -1,  0,  0,  0,  0 },
                {  -1, -1, -1, -1, -1, -1,  0, -1,  0,  0 },
                {   0,  0, -1,  0,  0,  0,  0,  0,  0,  0 },
                {   0,  0, -1,  0,  0,  0,  0,  0,  0,  0 },
            };

                var test = solver.Test(matrix, 10, 10);
                char[,] solvedCrossword = null;
                if (test)
                {
                    solvedCrossword = solver.FirstTest(10, 10);

                    //var s = string.Empty;
                    //for (int i = 0; i < solvedCrossword.GetLength(0); i++)
                    //{
                    //	for (int j = 0; j < solvedCrossword.GetLength(1); j++)
                    //	{
                    //		var t = solvedCrossword[i, j];
                    //		s += (t == '\0') ? '*' : t;
                    //	}
                    //	s += Environment.NewLine;
                    //}
                }
            }

            if (prevValue == recognizer.DetectedCenters.Count)
                prevCount++;
            _configuration["result"] = recognizer.DetectedCenters.Count;
            _configuration["centers"] = recognizer.DetectedCenters;
            prevValue = recognizer.DetectedCenters.Count;

            softwarebitmap.CopyTo(context.OutputFrame.SoftwareBitmap);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="bitmap"></param>
        private unsafe void EncodeStream(SoftwareBitmap bitmap)
        {
            using (BitmapBuffer buffer = bitmap.LockBuffer(BitmapBufferAccessMode.ReadWrite))
            using (var bufferReference = buffer.CreateReference())
            {

                if (bufferReference is IMemoryBufferByteAccess)
                {
                    byte* frameByte;
                    uint capacity;

                    ((IMemoryBufferByteAccess)bufferReference).GetBuffer(out frameByte, out capacity);

                    var bufferDescription = buffer.GetPlaneDescription(0);
                    byte[] frameData = new byte[bufferDescription.Height * bufferDescription.Width];
                    Marshal.Copy((IntPtr)frameByte, frameData, 0, frameData.Length);

                    encoder.Ffmpeg_encodeVideoFrame(frameData);
                }
            }
        }
        private unsafe void EncodeFrame(SoftwareBitmap frame)
        {

            RTMPEncoder encoder = new RTMPEncoder();
            encoder.Ffmpeg_init(400, 300, 128000, App.RTMPUrl);
            //encoder.Ffmpeg_encodeVideoFrame(data);
        }
		private static void OnThumbnailComplete(IImageProcessor processor, SoftwareBitmap softwareBitmap)
        {
            // Note: intentionally not awaited. We just deliver the thumbnail Bitmaps to the UI thread.
            TaskUtilities.RunOnDispatcherThreadAsync(() =>
            {
				WriteableBitmap writeableBitmap = new WriteableBitmap(softwareBitmap.PixelWidth, softwareBitmap.PixelHeight);
				softwareBitmap.CopyToBuffer(writeableBitmap.PixelBuffer);
				writeableBitmap.Invalidate();
                processor.ThumbnailImagSource = writeableBitmap;

                // The thumbnail image has been copied, so we can destroy the Bitmap.
                softwareBitmap.Dispose();
            });
        }
 public SoftwareBitmapLuminanceSource (SoftwareBitmap softwareBitmap) : base (softwareBitmap.PixelWidth, softwareBitmap.PixelHeight)
 {
     CalculateLuminance(softwareBitmap);
 }
Example #18
0
        private void LoadIDButton_Click(object sender, RoutedEventArgs e)
        {
            idStream = photoStream;
            idBitmap = photoBitmap;
            idBitmapSource = photoBitmapSource;

            IDPhoto.Source = idBitmapSource;
        }
Example #19
0
 private async void CameraButton_Click(object sender, RoutedEventArgs e)
 {
     photoStream = await camera.TakePhoto(CameraCaptureUIPhotoFormat.Jpeg);
     photoBitmap = await camera.ConvertToSoftwareBitmap(photoStream);
     photoBitmapSource = await camera.ConvertToSoftwareBitmapSource(photoBitmap);
 }
Example #20
0
        /// <summary>
        /// Loads image from file to bitmap and displays it in UI.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async Task LoadImage(StorageFile file)
        {
            using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                var decoder = await BitmapDecoder.CreateAsync(stream);

                bitmap = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);

                var imgSource = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);
                bitmap.CopyToBuffer(imgSource.PixelBuffer);
                PreviewImage.Source = imgSource;
            }
        }
Example #21
0
        protected override async void OnRun(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();

            // Create instance of the control that contains the layout of the Live Tile
            MediumTileControl control = new MediumTileControl();
            control.Width = TileWidth;
            control.Height = TileHeight;

            // If we have received a message in the parameters, overwrite the default "Hello, Live Tile!" one
            var triggerDetails = taskInstance.TriggerDetails as ApplicationTriggerDetails;
            if (triggerDetails != null)
            {
                object tileMessage = null;
                if (triggerDetails.Arguments.TryGetValue("Message", out tileMessage))
                {
                    if (tileMessage is string)
                    {
                        control.Message = (string)tileMessage;
                    }
                }
            }            

            // Render the tile control to a RenderTargetBitmap
            RenderTargetBitmap bitmap = new RenderTargetBitmap();
            await bitmap.RenderAsync(control, TileWidth, TileHeight);

            // Now we are going to save it to a PNG file, so create/open it on local storage
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(TileImageFilename, CreationCollisionOption.ReplaceExisting);
            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                // Create a BitmapEncoder for encoding to PNG
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                // Create a SoftwareBitmap from the RenderTargetBitmap, as it will be easier to save to disk
                using (var softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, TileWidth, TileHeight, BitmapAlphaMode.Premultiplied))
                {
                    // Copy bitmap data
                    softwareBitmap.CopyFromBuffer(await bitmap.GetPixelsAsync());

                    // Encode and save to file
                    encoder.SetSoftwareBitmap(softwareBitmap);
                    await encoder.FlushAsync();
                }
            }

            // Use the NotificationsExtensions library to easily configure a tile update
            TileContent mediumTileContent = new TileContent()
            {
                Visual = new TileVisual()
                {
                    TileMedium = new TileBinding()
                    {
                        Content = new TileBindingContentAdaptive()
                        {
                            BackgroundImage = new TileBackgroundImage()
                            {
                                Overlay = 0,
                                Source = new TileImageSource("ms-appdata:///local/" + TileImageFilename),
                            }
                        }
                    }
                }
            };

            // Clean previous update from Live Tile and update with the new parameters
            var tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            tileUpdater.Clear();
            tileUpdater.Update(new TileNotification(mediumTileContent.GetXml()));
            
            deferral.Complete();
        }
        private async Task<byte[]> SaveSoftwareBitmapToBufferAsync(SoftwareBitmap softwareBitmap)
        {
            byte[] bytes = null;

            try
            {
                IRandomAccessStream stream = new InMemoryRandomAccessStream();
                {
                    // Create an encoder with the desired format
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);

                    // Set the software bitmap
                    encoder.SetSoftwareBitmap(softwareBitmap);

                    // Set additional encoding parameters, if needed
                    //encoder.BitmapTransform.ScaledWidth = (uint)_width;
                    //encoder.BitmapTransform.ScaledHeight = (uint)_height;
                    //encoder.BitmapTransform.Rotation = Windows.Graphics.Imaging.BitmapRotation.Clockwise90Degrees;
                    //encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
                    encoder.IsThumbnailGenerated = false;

                    await encoder.FlushAsync();

                    bytes = new byte[stream.Size];

                    // This returns IAsyncOperationWithProgess, so you can add additional progress handling
                    await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, Windows.Storage.Streams.InputStreamOptions.None);
                }
            }

            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            return bytes;
        }
		private async Task<WriteableBitmap> ConvertPreviewToWriteableBitmap(SoftwareBitmap softwareBitmap, WriteableBitmap writeableBitmap)
		{
			int previewWidth = (int)m_renderer.PreviewSize.Width;
			int previewHeight = (int)m_renderer.PreviewSize.Height;

			if (writeableBitmap == null || writeableBitmap.PixelWidth != previewWidth || writeableBitmap.PixelHeight != previewHeight)
			{
				writeableBitmap = new WriteableBitmap(previewWidth, previewHeight);
			}

			if (softwareBitmap.PixelWidth != previewWidth || softwareBitmap.PixelHeight != previewHeight)
			{
				using (var renderer = new WriteableBitmapRenderer(new SoftwareBitmapImageSource(softwareBitmap)))
				{
					renderer.WriteableBitmap = writeableBitmap;

					await renderer.RenderAsync();
				}
			}
			else
			{
				softwareBitmap.CopyToBuffer(writeableBitmap.PixelBuffer);
			}

			writeableBitmap.Invalidate();
		
			return writeableBitmap;
		}
 public async Task<StorageFile> WriteToFile(WriteableBitmap wb)
 {
     SoftwareBitmap softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, wb.PixelWidth, wb.PixelHeight);
     softwareBitmap.CopyFromBuffer(wb.PixelBuffer);
     string fileName = Path.GetRandomFileName() + ".png";
     StorageFile file = null;
     if (softwareBitmap != null)
     {
         // save image file to cache
         file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);
         using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
         {
             BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
             encoder.SetSoftwareBitmap(softwareBitmap);
             await encoder.FlushAsync();
         }
     }
     return file;
 }
Example #25
0
        private async void LoadPortraitButton_Click(object sender, RoutedEventArgs e)
        {
            portraitStream = photoStream;
            portraitBitmap = photoBitmap;
            portraitBitmapSource = photoBitmapSource;

            PortraitPhoto.Source = portraitBitmapSource;

            portraitPath = await StorageAPI.SavePhoto(portraitStream, "Portrait");
        }
Example #26
0
        private async void InitializeCameraAsync()
        {
            sbSource = new SoftwareBitmapSource();
            receviebitMap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, 240, 180, 0);

            buffer = new Windows.Storage.Streams.Buffer((uint)(240 * 180 * 8));

            /*  stream client  close this */
            imageElement1.Source = sbSource;

            streamSocketSrv = new StreamSocketListenerServer();
            await streamSocketSrv.start(serverip, "22343");
          
            streamSocketClient = new StreamSocketClient();

            textBox.Text = clientip;
        }
        /// <summary>
        /// Applies a basic effect to a Bgra8 SoftwareBitmap in-place
        /// </summary>
        /// <param name="bitmap">SoftwareBitmap that will receive the effect</param>
        private unsafe void ApplyGreenFilter(SoftwareBitmap bitmap)
        {
            // Effect is hard-coded to operate on BGRA8 format only
            if (bitmap.BitmapPixelFormat == BitmapPixelFormat.Bgra8)
            {
                // In BGRA8 format, each pixel is defined by 4 bytes
                const int BYTES_PER_PIXEL = 4;

                using (var buffer = bitmap.LockBuffer(BitmapBufferAccessMode.ReadWrite))
                using (var reference = buffer.CreateReference())
                {
                    if (reference is IMemoryBufferByteAccess)
                    {
                        // Get a pointer to the pixel buffer
                        byte* data;
                        uint capacity;
                        ((IMemoryBufferByteAccess)reference).GetBuffer(out data, out capacity);

                        // Get information about the BitmapBuffer
                        var desc = buffer.GetPlaneDescription(0);

                        // Iterate over all pixels
                        for (uint row = 0; row < desc.Height; row++)
                        {
                            for (uint col = 0; col < desc.Width; col++)
                            {
                                // Index of the current pixel in the buffer (defined by the next 4 bytes, BGRA8)
                                var currPixel = desc.StartIndex + desc.Stride * row + BYTES_PER_PIXEL * col;

                                // Read the current pixel information into b,g,r channels (leave out alpha channel)
                                var b = data[currPixel + 0]; // Blue
                                var g = data[currPixel + 1]; // Green
                                var r = data[currPixel + 2]; // Red

                                // Boost the green channel, leave the other two untouched
                                data[currPixel + 0] = b;
                                data[currPixel + 1] = (byte)Math.Min(g + 80, 255);
                                data[currPixel + 2] = r;
                            }
                        }
                    }
                }
            }
        }
Example #28
0
            public static async Task <Windows.UI.Xaml.Media.Imaging.SoftwareBitmapSource> FromSoftwareBitmap(Windows.Graphics.Imaging.SoftwareBitmap bitmap)
            {
                var source = new Windows.UI.Xaml.Media.Imaging.SoftwareBitmapSource();
                await source.SetBitmapAsync(bitmap);

                return(source);
            }
 public static async Task<StorageFile> SoftwareBitmapSaveToFile(SoftwareBitmap softwareBitmap, StorageFile file)
 {
     if (softwareBitmap != null && file != null)
     {
         using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
         {
             BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
             encoder.SetSoftwareBitmap(softwareBitmap);
             await encoder.FlushAsync();
         }
     }
     return file;
 }
        /// <summary>
        /// Saves a SoftwareBitmap with the specified name
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        private static async Task SaveSoftwareBitmapAsync(SoftwareBitmap bitmap, StorageFile file)
        {
            using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream);

                // Grab the data from the SoftwareBitmap
                encoder.SetSoftwareBitmap(bitmap);
                await encoder.FlushAsync();
            }
        }
        public static WriteableBitmap SoftwareBitmapToWriteableBitmap(SoftwareBitmap softbitmap)
        {
            if (softbitmap == null)
                return null;

            WriteableBitmap bitmap = new WriteableBitmap(softbitmap.PixelWidth, softbitmap.PixelHeight);

            softbitmap.CopyToBuffer(bitmap.PixelBuffer);

            return bitmap;
        }
Example #32
0
        void TestCreateFromSoftwareBitmap(CanvasDevice device, BitmapPixelFormat pixelFormat, BitmapAlphaMode alphaMode)
        {
            if (pixelFormat == BitmapPixelFormat.Unknown)
                return;

            int anyWidth = 3;
            int anyHeight = 5;

            var softwareBitmap = new SoftwareBitmap(pixelFormat, anyWidth, anyHeight, alphaMode);

            if (!IsFormatSupportedByWin2D(pixelFormat, alphaMode))
            {
                Assert.ThrowsException<Exception>(() =>
                {
                    CanvasBitmap.CreateFromSoftwareBitmap(device, softwareBitmap);
                });
                return;
            }
            
            var canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(device, softwareBitmap);

            Assert.AreEqual(anyWidth, (int)canvasBitmap.SizeInPixels.Width);
            Assert.AreEqual(anyHeight, (int)canvasBitmap.SizeInPixels.Height);
            Assert.AreEqual(GetDirectXPixelFormatUsedForBitmapPixelFormat(pixelFormat), canvasBitmap.Format);

            CanvasAlphaMode expectedAlphaMode = CanvasAlphaMode.Straight;
            switch (alphaMode)
            {
                case BitmapAlphaMode.Ignore: expectedAlphaMode = CanvasAlphaMode.Ignore; break;
                case BitmapAlphaMode.Premultiplied: expectedAlphaMode = CanvasAlphaMode.Premultiplied; break;
                case BitmapAlphaMode.Straight: expectedAlphaMode = CanvasAlphaMode.Straight; break;
            }

            Assert.AreEqual(expectedAlphaMode, canvasBitmap.AlphaMode);
        }
        public static SoftwareBitmap WriteableBitmapToSoftwareBitmap(WriteableBitmap writeablebitmap)
        {
            if (writeablebitmap == null)
                return null;

            SoftwareBitmap softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, writeablebitmap.PixelWidth, writeablebitmap.PixelHeight);
            softwareBitmap.CopyFromBuffer(writeablebitmap.PixelBuffer);

            return softwareBitmap;
        }
        /// <summary>
        /// Saves a SoftwareBitmap to the Pictures library with the specified name
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        private static async Task SaveSoftwareBitmapAsync(SoftwareBitmap bitmap)
        {
            var file = await KnownFolders.PicturesLibrary.CreateFileAsync("PreviewFrame.jpg", CreationCollisionOption.GenerateUniqueName);
            using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream);

                // Grab the data from the SoftwareBitmap
                encoder.SetSoftwareBitmap(bitmap);
                await encoder.FlushAsync();
            }
        }
Example #35
0
 public static Task LogAsync(this SoftwareBitmap @this)
 {
     return(@this.LogAsync(string.Empty));
 }
        /// <summary>
        /// Transform image into Bgra8 image using given transform method.
        /// </summary>
        /// <param name="softwareBitmap">Input image to transform.</param>
        /// <param name="transformScanline">Method to map pixels in a scanline.</param>
        private static unsafe SoftwareBitmap TransformBitmap(SoftwareBitmap softwareBitmap, TransformScanline transformScanline)
        {
            // XAML Image control only supports premultiplied Bgra8 format.
            var outputBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8,
                softwareBitmap.PixelWidth, softwareBitmap.PixelHeight, BitmapAlphaMode.Premultiplied);

            using (var input = softwareBitmap.LockBuffer(BitmapBufferAccessMode.Read))
            using (var output = outputBitmap.LockBuffer(BitmapBufferAccessMode.Write))
            {
                // Get stride values to calculate buffer position for a given pixel x and y position.
                int inputStride = input.GetPlaneDescription(0).Stride;
                int outputStride = output.GetPlaneDescription(0).Stride;
                int pixelWidth = softwareBitmap.PixelWidth;
                int pixelHeight = softwareBitmap.PixelHeight;

                using (var outputReference = output.CreateReference())
                using (var inputReference = input.CreateReference())
                {
                    // Get input and output byte access buffers.
                    byte* inputBytes;
                    uint inputCapacity;
                    ((IMemoryBufferByteAccess)inputReference).GetBuffer(out inputBytes, out inputCapacity);
                    byte* outputBytes;
                    uint outputCapacity;
                    ((IMemoryBufferByteAccess)outputReference).GetBuffer(out outputBytes, out outputCapacity);

                    // Iterate over all pixels and store converted value.
                    for (int y = 0; y < pixelHeight; y++)
                    {
                        byte* inputRowBytes = inputBytes + y * inputStride;
                        byte* outputRowBytes = outputBytes + y * outputStride;

                        transformScanline(pixelWidth, inputRowBytes, outputRowBytes);
                    }
                }
            }
            return outputBitmap;
        }
        public static async Task<StorageFile> WriteableBitmapSaveToFile(WriteableBitmap wb, StorageFile file)
        {
            if (wb != null && file != null)
            {
                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    SoftwareBitmap softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, wb.PixelWidth, wb.PixelHeight);
                    softwareBitmap.CopyFromBuffer(wb.PixelBuffer);

                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream);
                    encoder.SetSoftwareBitmap(softwareBitmap);
                    await encoder.FlushAsync();
                }
            }
            return file;
        }