Example #1
0
        public static WriteableBitmap BuildColorBitmap(CTSliceInfo ct,
                                                       byte[,]     normalizedPixelBuffer)
        {
            byte[] imageDataArray = new byte[ct.RowCount * ct.ColumnCount * 4];

            int i = 0;
            for (int r = 0; r != ct.RowCount; ++r)
            {
                for (int c = 0; c != ct.ColumnCount; ++c)
                {
                    byte aGrayValue = normalizedPixelBuffer[r, c];

                    // Black/White image: all RGB values are set to same value
                    // Alpha value is set to 255
                    imageDataArray[i * 4] = aGrayValue;
                    imageDataArray[i * 4 + 1] = aGrayValue;
                    imageDataArray[i * 4 + 2] = aGrayValue;
                    imageDataArray[i * 4 + 3] = 255;

                    ++i;
                }
            }

            // Allocate the Bitmap
            WriteableBitmap bitmap = new WriteableBitmap(ct.ColumnCount, ct.RowCount, 96, 96, PixelFormats.Pbgra32, null);

            // Write the Pixels
            Int32Rect imageRectangle = new Int32Rect(0, 0, ct.ColumnCount, ct.RowCount);
            int imageStride = ct.ColumnCount * bitmap.Format.BitsPerPixel / 8;
            bitmap.WritePixels(imageRectangle, imageDataArray, imageStride, 0);

            return bitmap;
        }
Example #2
0
        public IconHandler(sd.Icon icon)
        {
            var rect = new sw.Int32Rect(0, 0, icon.Width, icon.Height);
            var img  = swi.Imaging.CreateBitmapSourceFromHIcon(icon.Handle, rect, swmi.BitmapSizeOptions.FromEmptyOptions());

            Control = swmi.BitmapFrame.Create(img);
        }
Example #3
0
        public void AddFrame(string path, Int32Rect rect, int delay = 66)
        {
            //TODO: If global color is used, get all colors from all frames and write only 1 color table.
            GeneratePalette(path);

            CalculateColorTableSize();

            if (IsFirstFrame)
            {
                FullSize = rect;

                WriteLogicalScreenDescriptor(rect);

                //Global color table.
                if (UseGlobalColorTable)
                    WritePalette();

                if (RepeatCount > -1)
                    WriteApplicationExtension();
            }

            WriteGraphicControlExtension(delay);
            WriteImageDescriptor(rect);

            //TODO: If it has Global color table, no need to use local.
            //if uses global, all colors should be added to that palette.

            //Local color table.
            if (!UseGlobalColorTable)
                WritePalette();

            WriteImage();

            IsFirstFrame = false;
        }
      private void CalculateLuminanceRGB(BitmapSource bitmap)
      {
         var width = bitmap.PixelWidth;
         var height = bitmap.PixelHeight;
         var stepX = (bitmap.Format.BitsPerPixel + 7) / 8;
         var bufferSize = width * stepX;
         var buffer = new byte[bufferSize];
         var rect = new Int32Rect(0, 0, width, 1);
         var luminanceIndex = 0;

         luminances = new byte[width * height];

         for (var curY = 0; curY < height; curY++)
         {
            bitmap.CopyPixels(rect, buffer, bufferSize, 0);
            for (var curX = 0; curX < bufferSize; curX += stepX)
            {
               var r = buffer[curX];
               var g = buffer[curX + 1];
               var b = buffer[curX + 2];
               luminances[luminanceIndex] = (byte)
                  (0.3 * r + 0.59 * g + 0.11 * b + 0.01);
               luminanceIndex++;
            }
            rect.Y++;
         }
      }
Example #5
0
        //セットアップ
        public KinectImage()
        #region
        {
            //キネクト
            this.kinect = KinectSensor.GetDefault();
            
            //bodyIndexFrameの処理
            this.bodyIndexFrameDes = this.kinect.BodyIndexFrameSource.FrameDescription;
            this.bodyIndexFrameReader = this.kinect.BodyIndexFrameSource.OpenReader();
            this.bodyIndexFrameReader.FrameArrived += this.BodyIndexFrame_Arrived;
            //画像情報
            this.kinectImgPackage = new ShadowPackage();
            this.imageWidth =  this.bodyIndexFrameDes.Width;  // imgW;
            this.imageHeight = this.bodyIndexFrameDes.Height; // imgH;

            this.imageBytePerPixel = (int)this.bodyIndexFrameDes.BytesPerPixel;
            this.bitmapRec = new Int32Rect(0, 0, this.imageWidth, this.imageHeight);
            this.bitmapStride = (int)(this.imageWidth * this.imageBytePerPixel);
           
            this.bodyIndexBuffer = new byte[this.imageWidth *
                                                this.imageHeight * this.imageBytePerPixel];
            this.kinectImage = new Mat(this.imageHeight, this.imageWidth, MatType.CV_8UC1);
            //キネクト開始
            this.kinect.Open();
            
        }
        public Color GetPixelColor(int x, int y) {
            Color color;
            var bytesPerPixel = (_screenSource.Format.BitsPerPixel + 7) / 8;
            var bytes = new byte[bytesPerPixel];
            var rect = new Int32Rect(x, y, 1, 1);

            _screenSource.CopyPixels(rect, bytes, bytesPerPixel, 0);
            
            if (_screenSource.Format == PixelFormats.Pbgra32) {
                color = Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]);
            } else if (_screenSource.Format == PixelFormats.Bgr32) {
                color = Color.FromArgb(0xFF, bytes[2], bytes[1], bytes[0]);
            } else if (_screenSource.Format == PixelFormats.Bgra32) {
                color = Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]);
            } else {
                if (!_hasBeenWarned) {
                    Logging.Warning("Unsupported format: " + _screenSource.Format);
                    _hasBeenWarned = true;
                }

                color = Colors.Black;
            }

            return color;
        }
 public void Init(
   CoordinateMapper mapper,
   Int32Rect colourFrameSize)
 {
     canvasCoordMapper = new CanvasCoordMapper(canvas,
       mapper, colourFrameSize);
 }
Example #8
0
        public async Task EncodeColorAsync(byte[] colorData, BinaryWriter writer)
        {
            if (this.Width == this.OutputWidth && this.Height == this.OutputHeight)
            {
                // Header
                writer.Write(this.Width);
                writer.Write(this.Height);
                writer.Write(colorData.Length);

                // Data
                writer.Write(colorData);
            }
            else
            {
                WriteableBitmap bmp = BitmapFactory.New(this.Width, this.Height);
                int stride = this.Width * 4; // 4 bytes per pixel in BGRA
                var dirtyRect = new Int32Rect(0, 0, this.Width, this.Height);
                bmp.WritePixels(dirtyRect, colorData, stride, 0);
                var newBytes = await Task.FromResult(bmp.Resize(this.OutputWidth, this.OutputHeight, WriteableBitmapExtensions.Interpolation.NearestNeighbor).ToByteArray());

                // Header
                writer.Write(this.OutputWidth);
                writer.Write(this.OutputHeight);
                writer.Write(newBytes.Length);
                writer.Write(newBytes);

            }
        }
        public void Update(ImageFrameReadyEventArgs e)
        {
            if (depthFrame32 == null)
            {
                depthFrame32 = new byte[e.ImageFrame.Image.Width * e.ImageFrame.Image.Height * 4];
            }

            ConvertDepthFrame(e.ImageFrame.Image.Bits);

            if (DepthBitmap == null)
            {
                DepthBitmap = new WriteableBitmap(e.ImageFrame.Image.Width, e.ImageFrame.Image.Height, 96, 96, PixelFormats.Bgra32, null);
            }

            DepthBitmap.Lock();

            int stride = DepthBitmap.PixelWidth * DepthBitmap.Format.BitsPerPixel / 8;
            Int32Rect dirtyRect = new Int32Rect(0, 0, DepthBitmap.PixelWidth, DepthBitmap.PixelHeight);
            DepthBitmap.WritePixels(dirtyRect, depthFrame32, stride, 0);

            DepthBitmap.AddDirtyRect(dirtyRect);
            DepthBitmap.Unlock();

            RaisePropertyChanged(()=>DepthBitmap);
        }
Example #10
0
 private void Init(int width, int height)
 {
   
     _bitmap = BitmapFactory.New(width, height);
     _bytes = new byte[width * height * 4];
     _dirtyRect = new Int32Rect(0, 0, width, height);
 }
Example #11
0
        public static ImageSource GetDirectoryIcon(string path, int iconIndex, IconSize size = IconSize.Small)
        {
            ImageSource imageSource = null;

                if (IconsDictionary.TryGetValue(iconIndex, out imageSource))
                {
                    return imageSource;
                }
                Int32Rect sizeRect;
                WinAPI.SHGFI flags;
                if (IconSize.Small == size)
                {
                    flags = commonFlags | WinAPI.SHGFI.SHGFI_SMALLICON;
                    sizeRect = new Int32Rect(0, 0, 16, 16);
                }
                else
                {
                    flags = commonFlags | WinAPI.SHGFI.SHGFI_LARGEICON;
                    sizeRect = new Int32Rect(0, 0, 32, 32);
                }
                WinAPI.SHFILEINFO shfileinfo = new WinAPI.SHFILEINFO();
                WinAPI.SHGetFileInfo(path, 256, out shfileinfo, (uint) Marshal.SizeOf(shfileinfo), flags);
                if (shfileinfo.hIcon == IntPtr.Zero)
                {
                    return GetIcon(path);
                }
                imageSource = Imaging.CreateBitmapSourceFromHIcon(shfileinfo.hIcon, sizeRect,
                    BitmapSizeOptions.FromEmptyOptions());
                IconsDictionary.Add(iconIndex, imageSource);
                WinAPI.DestroyIcon(shfileinfo.hIcon);
                shfileinfo.hIcon = IntPtr.Zero;

                return imageSource;
        }
        public BitmapSource BpsCrop(BitmapSource bmpSource)
        {
            Rect rcInterior = _prCropMask.RectInterior;

            Point pxFromSize = UnitsToPx(rcInterior.Width, rcInterior.Height);

            Point pxFromPos = UnitsToPx(rcInterior.Left, rcInterior.Top);
            Point pxWhole   = UnitsToPx(AdornedElement.RenderSize.Width, AdornedElement.RenderSize.Height);

            pxFromSize.X = Math.Max(Math.Min(pxWhole.X - pxFromPos.X, pxFromSize.X), 0);
            pxFromSize.Y = Math.Max(Math.Min(pxWhole.Y - pxFromPos.Y, pxFromSize.Y), 0);
            if (pxFromSize.X == 0 || pxFromSize.Y == 0)
            {
                return(null);
            }

            //both ratios should be the same, but for safety, we will use two values
            double ratioX = bmpSource.PixelWidth / (double)pxWhole.X;
            double ratioY = bmpSource.PixelHeight / (double)pxWhole.Y;

            //set CropZone property
            this.CropZone = new Size((ratioX * pxFromSize.X), (ratioY * pxFromSize.Y));
            //multiply each position by ratio of dimensions of original image size and rendered image size
            System.Windows.Int32Rect rcFrom = new System.Windows.Int32Rect((int)(ratioX * pxFromPos.X), (int)(ratioY * pxFromPos.Y),
                                                                           (int)CropZone.Width, (int)CropZone.Height);

            return(new CroppedBitmap(bmpSource, rcFrom));
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var exposure = value as Exposure;

            if (exposure != null)
            {
                if (_exposureBitmap == null ||
                    ((int)_exposureBitmap.Width != exposure.Width || (int)_exposureBitmap.Height != exposure.Height))
                {
                    _exposureBitmap = new WriteableBitmap(exposure.Width, exposure.Height, 96, 96,
                        PixelFormats.Gray8, null);

                }
                var fullRect = new Int32Rect(0, 0, (int) _exposureBitmap.Width, (int) _exposureBitmap.Height);

                GCHandle pinnedExposureBuf = GCHandle.Alloc(exposure.Pixels8Bit, GCHandleType.Pinned);
                IntPtr exposureBufPtr = pinnedExposureBuf.AddrOfPinnedObject();

                for (int i = 0; i < exposure.Height; i++)
                {
                    int skip = i*_exposureBitmap.BackBufferStride;
                    int ppos = i*exposure.Width;
                    CopyMemory(_exposureBitmap.BackBuffer + skip, exposureBufPtr + ppos, (uint)exposure.Width);
                }

                _exposureBitmap.Lock();
                _exposureBitmap.AddDirtyRect(fullRect);
                _exposureBitmap.Unlock();

                return _exposureBitmap;

            }

            return null;
        }
        public MainWindow()
        {
            InitializeComponent();
            try
            {

                CompositionTarget.Rendering += CompositionTarget_Rendering;

                //_kC.InitialCalibration();
                this._colorImageBitmapRect = new Int32Rect(0, 0, 640, 480);
                this._colorImageStride = 640 * 4;

                this._colorImageBitmap1 = new WriteableBitmap(640, 480, 96, 96, PixelFormats.Bgr32, null);
                this._colorImageBitmap2 = new WriteableBitmap(640, 480, 96, 96, PixelFormats.Bgr32, null);
                this._colorImageBitmap3 = new WriteableBitmap(640, 480, 96, 96, PixelFormats.Bgr32, null);
                this._colorImageBitmap4 = new WriteableBitmap(640, 480, 96, 96, PixelFormats.Bgr32, null);
                this._colorImageBitmap5 = new WriteableBitmap(640, 480, 96, 96, PixelFormats.Bgr32, null);

                this.ColorImageElement1.Source = this._colorImageBitmap1;
                this.ColorImageElement2.Source = this._colorImageBitmap2;
                this.ColorImageElement3.Source = this._colorImageBitmap3;
                this.ColorImageElement4.Source = this._colorImageBitmap4;
                this.ColorImageElement5.Source = this._colorImageBitmap5;

                //this.ColorImageElement1.Source = kC.GetDifferenceBitmap();

                //this.ColorImageElement3.Source = kC.GetPic2Bitmap();

            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.StackTrace);
            }
        }
        private void CreateUVImage()
        {
            this.Bitmap.Lock();

            var rect = new Int32Rect(0, 0, Bitmap.PixelWidth, Bitmap.PixelHeight);
            var bytesPerPixel = (Bitmap.Format.BitsPerPixel + 7) / 8; // 1 ピクセル当たりのバイト数(4 になるはず)
            var stride = Bitmap.PixelWidth * bytesPerPixel; // 幅方向のバイト数
            var arraySize = stride * Bitmap.PixelHeight;

            pixelEntity = new byte[arraySize];

            int index; // 左上隅からのバイトのインデックス

            for (int y = 0; y < Bitmap.PixelHeight; ++y)
            {
                for (int x = 0; x < Bitmap.PixelWidth; ++x)
                {
                    index = x * bytesPerPixel + y * stride;

                    var r = (byte)(((double)x / Bitmap.PixelWidth) * 255);
                    var g = (byte)(((double)y / Bitmap.PixelHeight) * 255);

                    pixelEntity[index] = 0;
                    pixelEntity[index + 1] = g;
                    pixelEntity[index + 2] = r;
                    pixelEntity[index + 3] = 255;
                }
            }
            Bitmap.WritePixels(rect, pixelEntity, stride, 0);

            this.Bitmap.Unlock();
        }
Example #16
0
 /// <summary>
 /// Update the bitmap with the given byte array.
 /// </summary>
 /// <param name="data">the length of the data must be equal to this.width * this.height</param>
 public void UpdateBitmap(byte[] data, WriteableBitmap bitmap)
 {
     var stride = bitmap.PixelWidth * bitmap.Format.BitsPerPixel / 8;
       var rect = new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight);
       bitmap.WritePixels(rect, data, stride, 0);
       RaisePropertyChanged(() => bitmap);
 }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <remarks>
        /// Created by default automatically.
        /// </remarks>
        public MainWindow()
        {
            InitializeComponent();

            int width = (int)Math.Ceiling(Math.Sqrt(sn_range));
            int height = width;

            m_shuffledBuffer = new WriteableBitmap(width, height, 96, 96, PixelFormats.Cmyk32, null);
            m_sortedBuffer = new WriteableBitmap(width, height, 96, 96, PixelFormats.Cmyk32, null);
            m_rect = new Int32Rect(0, 0, m_sortedBuffer.PixelWidth, m_sortedBuffer.PixelHeight);
            m_bpp = (m_sortedBuffer.Format.BitsPerPixel + 7) / 8;
            m_stride = m_sortedBuffer.PixelWidth * m_bpp;
            m_arraySize = m_stride * m_sortedBuffer.PixelHeight;

            imgSorted.Source = m_sortedBuffer;
            imgShuffled.Source = m_shuffledBuffer;

            imgShuffled.Width = width;
            imgShuffled.Height = height;

            imgSorted.Width = width;
            imgSorted.Height = height;

            txtOutput.IsReadOnly = true;
        }
        public unsafe void CreateImage(WriteableBitmap target, IntPtr pointer)
        {
            Int32Rect rectangle = default(Int32Rect);
            target.Dispatcher.Invoke(new Action(() =>
            {
                rectangle = new Int32Rect(0, 0, target.PixelWidth, target.PixelHeight);
            }));

            this.CreateHistogram(pointer, rectangle.Width, rectangle.Height);
            var pixelcount = rectangle.Width * rectangle.Height;
            var buffer = new byte[pixelcount * 3];
            try
            {
                ushort* pDepth = (ushort*)pointer;
                for (int index = 0; index < pixelcount; index++)
                {
                    byte pixel = (byte)histogram.GetValue(*pDepth);
                    buffer[index * 3] = pixel;
                    buffer[index * 3 + 1] = pixel;
                    buffer[index * 3 + 2] = pixel;
                    pDepth++;
                }
            }
            catch (AccessViolationException)
            { }
            catch (SEHException)
            { }

            target.Dispatcher.Invoke(new Action(() =>
                {
                    target.Lock();
                    target.WritePixels(rectangle, buffer, rectangle.Width * 3, 0);
                    target.Unlock();
                }));
        }
        public unsafe void CreateImage(WriteableBitmap target, IntPtr pointer)
        {
            Int32Rect rectangle = default(Int32Rect);
            target.Dispatcher.Invoke(new Action(() => 
                {
                    rectangle = new Int32Rect(0, 0, target.PixelWidth, target.PixelHeight);
                }));

            byte* pImage = (byte*)pointer.ToPointer();

            var pixelCount = rectangle.Width * rectangle.Height;
            var buffer = new byte[pixelCount * 3];

            for (int index = 0; index < pixelCount; index++)
            {
                buffer[index * 3] = pImage[2];
                buffer[index * 3 + 1] = pImage[1];
                buffer[index * 3 + 2] = pImage[0];
                pImage += 3;
            }

            target.Dispatcher.Invoke(new Action(() =>
            {
                target.Lock();
                target.WritePixels(rectangle, buffer, rectangle.Width * 3, 0);
                target.Unlock();
            }));
        }
Example #20
0
        public CardPack()
        {
            _pack = new List<Card>();
            Uri uri = new Uri("./Images/cards.png", UriKind.Relative);
            source = new BitmapImage(uri);
            _cardFronts = new List<CroppedBitmap>();
            CardBack = new Image();

            int w = source.PixelWidth / 13;
            int h = source.PixelHeight/5;

            for (int s = 0; s < 4; s++)
            {
                for (int v = 0; v < 13; v++)
                {
                    int imageIndex = (s*13) + v;

                    int fx = imageIndex % 13;
                    int fy = imageIndex / 13;

                    Int32Rect sourceRect = new Int32Rect(fx * w, fy * h, w, h);
                    CroppedBitmap front = new CroppedBitmap(source, sourceRect);

                    sourceRect = new Int32Rect(2 * w, 4 * h, w, h);
                    CroppedBitmap back = new CroppedBitmap(source, sourceRect);

                    Image frontImage = new Image {Source = front};
                    Image backImage = new Image { Source = back };

                    Card card = new Card((CardSuit)s, (CardValue)v, frontImage, backImage);
                    _pack.Add(card);
                }
            }
        }
Example #21
0
        /// <summary>
        /// Generates an image of each page in the year book
        /// and saves it to the src folder
        /// </summary>
        /// <param name="bv"></param>
        /// <param name="folderloc"></param>
        private static void RenderPages(BookViewer bv, string folderloc)
        {
            int currentpage = bv.ViewIndex;
            //loops though each page
            foreach (Page p in bv.CurrentBook.Pages)
            {
                bv.ViewIndex = p.PageNumber;
                //forces the canvas to re-render
                BookViewer.DesignerCanvas.UpdateLayout();
                //takes a picture of the canvas
                RenderTargetBitmap rtb = new RenderTargetBitmap(PaperSize.Pixel.PaperWidth, PaperSize.Pixel.PaperHeight, 96, 96, PixelFormats.Default);
                rtb.Render(BookViewer.DesignerCanvas);
                //getting the bleed margin
                Int32Rect bleedmargin = new Int32Rect((PaperSize.Pixel.PaperWidth - PaperSize.Pixel.BleedWidth) / 2, (PaperSize.Pixel.PaperHeight - PaperSize.Pixel.BleedHeight) / 2, PaperSize.Pixel.BleedWidth, PaperSize.Pixel.BleedHeight);
                //cropping the image
                CroppedBitmap cb = new CroppedBitmap(rtb, bleedmargin);
                //encodes the image in png format
                PngBitmapEncoder pbe = new PngBitmapEncoder();
                pbe.Frames.Add(BitmapFrame.Create(cb));
                //saves the resulting image
                FileStream fs = File.Open(folderloc + "\\src\\" + (p.PageNumber+1) + ".png", FileMode.Create);
                pbe.Save(fs);
                fs.Flush();
                fs.Close();

            }
            bv.ViewIndex = currentpage;
        }
Example #22
0
        public Color GetPixel(int x, int y)
        {
            var rect    = new sw.Int32Rect(x, y, 1, 1);
            var control = FrozenControl;

            var pixelStride = (rect.Width * control.Format.BitsPerPixel + 7) / 8;

            var pixels = new byte[pixelStride * rect.Height];

            control.CopyPixels(rect, pixels, stride: pixelStride, offset: 0);

            if (control.Format == swm.PixelFormats.Rgb24)
            {
                return(Color.FromArgb(red: pixels[0], green: pixels[1], blue: pixels[2]));
            }
            if (control.Format == swm.PixelFormats.Bgr24)
            {
                return(Color.FromArgb(blue: pixels[0], green: pixels[1], red: pixels[2]));
            }
            if (control.Format == swm.PixelFormats.Bgr32)
            {
                return(Color.FromArgb(blue: pixels[0], green: pixels[1], red: pixels[2]));
            }
            if (control.Format == swm.PixelFormats.Bgra32)
            {
                return(Color.FromArgb(blue: pixels[0], green: pixels[1], red: pixels[2], alpha: pixels[3]));
            }
            if (control.Format == swm.PixelFormats.Pbgra32)
            {
                return(Color.FromPremultipliedArgb(blue: pixels[0], green: pixels[1], red: pixels[2], alpha: pixels[3]));
            }
            throw new NotSupportedException();
        }
Example #23
0
        unsafe bool Close()
        {
            CloseGroup();
            if (image != null)
            {
                Control.Close();
                var handler = (BitmapHandler)image.Handler;
                var bmp     = image.ToWpf();
                var newbmp  = new swmi.RenderTargetBitmap(bmp.PixelWidth, bmp.PixelHeight, bmp.DpiX, bmp.DpiY, swm.PixelFormats.Pbgra32);
                newbmp.RenderWithCollect(visual);
                if (!bmp.Format.HasAlpha())
                {
                    // convert to non-alpha, as RenderTargetBitmap does not support anything other than Pbgra32
                    var wb     = new swmi.WriteableBitmap(bmp.PixelWidth, bmp.PixelHeight, bmp.DpiX, bmp.DpiY, swm.PixelFormats.Bgr32, null);
                    var rect   = new sw.Int32Rect(0, 0, bmp.PixelWidth, bmp.PixelHeight);
                    var pixels = new byte[bmp.PixelHeight * wb.BackBufferStride];
                    newbmp.CopyPixels(rect, pixels, wb.BackBufferStride, 0);
                    fixed(byte *ptr = pixels)
                    {
                        wb.WritePixels(rect, (IntPtr)ptr, pixels.Length, wb.BackBufferStride, 0, 0);
                    }

                    handler.SetBitmap(wb);
                }
                else
                {
                    handler.SetBitmap(newbmp);
                }
                return(true);
            }
            return(false);
        }
        /// <summary>Creates the screenshot of entire plotter element</summary>
        /// <returns></returns>
        internal static BitmapSource CreateScreenshot(UIElement uiElement, Int32Rect screenshotSource)
        {
            Window window = Window.GetWindow(uiElement);
            if (window == null)
            {
                return CreateElementScreenshot(uiElement);
            }
            Size size = window.RenderSize;

            //double dpiCoeff = 32 / SystemParameters.CursorWidth;
            //int dpi = (int)(dpiCoeff * 96);
            double dpiCoeff = 1;
            int dpi = 96;

            RenderTargetBitmap bmp = new RenderTargetBitmap(
                (int)(size.Width * dpiCoeff), (int)(size.Height * dpiCoeff),
                dpi, dpi, PixelFormats.Default);

			// white background
			Rectangle whiteRect = new Rectangle { Width = size.Width, Height = size.Height, Fill = Brushes.White };
			whiteRect.Measure(size);
			whiteRect.Arrange(new Rect(size));
			bmp.Render(whiteRect);
			// the very element
            bmp.Render(uiElement);

            CroppedBitmap croppedBmp = new CroppedBitmap(bmp, screenshotSource);
            return croppedBmp;
        }
Example #25
0
 public Figure(int figureIdx, int pageIdx, Int32Rect figRect, string[] triggerTxt)
 {
     this.PageIndex = pageIdx;
       this.FigureIndex = figureIdx;
       this.FigureRect = figRect;
       this.TriggerText = triggerTxt;
 }
Example #26
0
        public Color GetPixel(int x, int y)
        {
            return(ApplicationHandler.InvokeIfNecessary(() =>
            {
                var rect = new sw.Int32Rect(x, y, 1, 1);

                var pixelStride = (rect.Width * Control.Format.BitsPerPixel + 7) / 8;

                var pixels = new byte[pixelStride * rect.Height];

                Control.CopyPixels(rect, pixels, stride: pixelStride, offset: 0);

                if (Control.Format == swm.PixelFormats.Rgb24)
                {
                    return Color.FromArgb(red: pixels[0], green: pixels[1], blue: pixels[2]);
                }
                if (Control.Format == swm.PixelFormats.Bgr32)
                {
                    return Color.FromArgb(blue: pixels[0], green: pixels[1], red: pixels[2]);
                }
                if (Control.Format == swm.PixelFormats.Bgra32)
                {
                    return Color.FromArgb(blue: pixels[0], green: pixels[1], red: pixels[2], alpha: pixels[3]);
                }
                if (Control.Format == swm.PixelFormats.Pbgra32)
                {
                    return Color.FromArgb(blue: pixels[0], green: pixels[1], red: pixels[2], alpha: pixels[3]);
                }
                throw new NotSupportedException();
            }));
        }
        public WriteableBitmap Render(int[] values)
        {
            if (values.Length != this.pixels.Length)
            {
                throw new ArgumentException("Number of raw values must equal width*height");
            }

            // Convert raw values to ARGB format pixels.
            this.ConvertToPixels(values);

            // Copy pixels to frame buffer.
            var bitmap = new WriteableBitmap(   this.width,
                                                this.height,
                                                0,
                                                0,
                                                PixelFormats.Pbgra32,
                                                null);
            int widthInBytes = 4 * this.width;
            var sourceRect = new Int32Rect(0, 0, this.width, this.height);
            bitmap.WritePixels( sourceRect,
                                pixels,
                                widthInBytes,
                                0);

            return bitmap;
        }
Example #28
0
        public BitmapSource BpsCrop()
        {
            Thickness margin     = AdornerMargin();
            Rect      rcInterior = _prCropMask.RectInterior;

            Point pxFromSize = UnitsToPx(rcInterior.Width, rcInterior.Height);

            // It appears that CroppedBitmap indexes from the upper left of the margin whereas RenderTargetBitmap renders the
            // control exclusive of the margin.  Hence our need to take the margins into account here...

            Point pxFromPos = UnitsToPx(rcInterior.Left + margin.Left, rcInterior.Top + margin.Top);
            Point pxWhole   = UnitsToPx(AdornedElement.RenderSize.Width + margin.Left, AdornedElement.RenderSize.Height + margin.Left);

            pxFromSize.X = Math.Max(Math.Min(pxWhole.X - pxFromPos.X, pxFromSize.X), 0);
            pxFromSize.Y = Math.Max(Math.Min(pxWhole.Y - pxFromPos.Y, pxFromSize.Y), 0);
            if (pxFromSize.X == 0 || pxFromSize.Y == 0)
            {
                return(null);
            }
            System.Windows.Int32Rect rcFrom = new System.Windows.Int32Rect(pxFromPos.X, pxFromPos.Y, pxFromSize.X, pxFromSize.Y);

            RenderTargetBitmap rtb = new RenderTargetBitmap(pxWhole.X, pxWhole.Y, s_dpiX, s_dpiY, PixelFormats.Default);

            rtb.Render(AdornedElement);
            return(new CroppedBitmap(rtb, rcFrom));
        }
Example #29
0
        public void Initialize(KinectSensor sensor)
        {
            this.sensor = sensor;
            coordinateMapper = new CoordinateMapper(sensor);

            //Prepare for RGB image information receive
            sensor.ColorStream.Enable(ColorImageFormat.RgbResolution1280x960Fps12);
            imageSize = new Int32Rect(0, 0, sensor.ColorStream.FrameWidth, sensor.ColorStream.FrameHeight);
            stride = imageSize.Width * 4; // blue, green, red, empty
            colorData = new byte[sensor.ColorStream.FramePixelDataLength];
            ColorBitmap = new WriteableBitmap(imageSize.Width, imageSize.Height, 96, 96, PixelFormats.Bgr32, null);

            TransformSmoothParameters smooth = new TransformSmoothParameters()
            {
                Smoothing = Parameters.Kinect.Smoothing,
                Correction = Parameters.Kinect.Correction,
                Prediction = Parameters.Kinect.Prediction,
                JitterRadius = Parameters.Kinect.JitterRadius,
                MaxDeviationRadius = Parameters.Kinect.MaxDeviationRadius
            };
            sensor.SkeletonStream.TrackingMode = Parameters.Kinect.TrackingMode;
            sensor.SkeletonStream.Enable(smooth);

            sensor.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(sensor_SkeletonFrameReady);
            sensor.ColorFrameReady += new EventHandler<ColorImageFrameReadyEventArgs>(sensor_ColorFrameReady);
            sensor.Start();
            Initialized = true;
        }
Example #30
0
        public void Draw(List<Cell> alives)
        {
            int width = Cells.GetLength(0);
            int height = Cells.GetLength(1);

            // Reserve the back buffer for updates
            WriteableBitmap bitmap = _bitmap;
            bitmap.Lock();

            // Clear to white
            var rect = new Int32Rect(0, 0, width, height);
            bitmap.WritePixels(rect, _whiteBitmap, bitmap.BackBufferStride, 0);

            unsafe
            {
                // Get a pointer to the back buffer
                int pBackBuffer = (int)bitmap.BackBuffer;
                foreach (Cell cell in alives)
                {
                    // Find the address of the pixel to draw
                    int p = pBackBuffer + (cell.Y * bitmap.BackBufferStride);
                    p += cell.X * 4;
                    *((int*)p) = 0;
                }
            }

            // Specify the area of the bitmap that changed
            bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));

            // Release the back buffer and make it available for display
            bitmap.Unlock();
        }
        public void Show(Int32Rect rpRect)
        {
            var rMainWindowHandle = new WindowInteropHelper(App.Current.MainWindow).Handle;

            if (r_HwndSource == null)
            {
                var rParam = new HwndSourceParameters(nameof(ScreenshotToolOverlayWindow))
                {
                    Width = 0,
                    Height = 0,
                    PositionX = 0,
                    PositionY = 0,
                    WindowStyle = 0,
                    UsesPerPixelOpacity = true,
                    HwndSourceHook = WndProc,
                    ParentWindow = rMainWindowHandle,
                };

                r_HwndSource = new HwndSource(rParam) { SizeToContent = SizeToContent.Manual, RootVisual = this };
            }

            var rBrowserWindowHandle = ServiceManager.GetService<IBrowserService>().Handle;

            NativeStructs.RECT rBrowserWindowRect;
            NativeMethods.User32.GetWindowRect(rBrowserWindowHandle, out rBrowserWindowRect);

            var rHorizontalRatio = rBrowserWindowRect.Width / GameConstants.GameWidth;
            var rVerticalRatio = rBrowserWindowRect.Height / GameConstants.GameHeight;
            rpRect.X = (int)(rpRect.X * rHorizontalRatio);
            rpRect.Y = (int)(rpRect.Y * rVerticalRatio);
            rpRect.Width = (int)(rpRect.Width * rHorizontalRatio);
            rpRect.Height = (int)(rpRect.Height * rVerticalRatio);

            NativeMethods.User32.SetWindowPos(r_HwndSource.Handle, IntPtr.Zero, rBrowserWindowRect.Left + rpRect.X, rBrowserWindowRect.Top + rpRect.Y, rpRect.Width, rpRect.Height, NativeEnums.SetWindowPosition.SWP_NOZORDER | NativeEnums.SetWindowPosition.SWP_NOACTIVATE | NativeEnums.SetWindowPosition.SWP_SHOWWINDOW);
        }
        private void Window_Loaded( object sender, RoutedEventArgs e )
        {
            try {
                kinect = KinectSensor.GetDefault();
                if ( kinect == null ) {
                    throw new Exception("Kinectを開けません");
                }

                kinect.Open();

                // 表示のためのデータを作成
                depthFrameDesc = kinect.DepthFrameSource.FrameDescription;

                // 表示のためのビットマップに必要なものを作成
                depthImage = new WriteableBitmap( depthFrameDesc.Width, depthFrameDesc.Height,
                    96, 96, PixelFormats.Gray16, null );
                depthBuffer = new ushort[depthFrameDesc.LengthInPixels];
                depthRect = new Int32Rect( 0, 0, depthFrameDesc.Width, depthFrameDesc.Height );
                depthStride = (int)(depthFrameDesc.Width * depthFrameDesc.BytesPerPixel);

                ImageDepth.Source = depthImage;

                // 初期の位置表示座標
                depthPoint = new Point( depthFrameDesc.Width / 2, depthFrameDesc.Height / 2 );

                // Depthリーダーを開く
                depthFrameReader = kinect.DepthFrameSource.OpenReader();
                depthFrameReader.FrameArrived += depthFrameReader_FrameArrived;
            }
            catch ( Exception ex ) {
                MessageBox.Show( ex.Message );
                Close();
            }
        }
Example #33
0
        public void RedrawAggregate(ref WriteableBitmap bitmap)
        {
            try
            {
                ChartArray_Redraw(chartArray);

                IntPtr ptr = ChartArray_GetAggregateImagePtr(chartArray);

                if (ptr != IntPtr.Zero)
                {
                    int width  = (int)bitmap.Width;
                    int height = (int)bitmap.Height;

                    System.Windows.Int32Rect rect = new System.Windows.Int32Rect(0, 0, width, height);

                    bitmap.Lock();
                    bitmap.WritePixels(rect, ptr, width * height * 4, width * 4);
                    bitmap.Unlock();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Marshaling Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #34
0
        public void RenderMaterial()
        {
            int width = (int)Width;
            int height = (int)Height;

            byte[] pixels = new byte[4 * height * width];
            WriteableBitmap writeableBitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);

            for (int p=0; p<width*height; p++)
            {
                Colour fillColour = _Material._DiffuseColour;
                fillColour.Clamp(0, 1);
                pixels[p*4] = (byte)(fillColour._Blue * 255.99f);
                pixels[p*4+1] = (byte)(fillColour._Green * 255.99f); 
                pixels[p*4+2] = (byte)(fillColour._Red * 255.99f); 
                pixels[p*4+3] = 255;
            }

            Int32Rect rect = new Int32Rect(0, 0, width, height);

            writeableBitmap.WritePixels(rect, pixels, width * 4, (int)0);

            MaterialImage.Source = writeableBitmap;

        }
 private static ImageSource GetImageSource()
 {
     BitmapSource source = ImageHelper.BitmapSourceFromBitmap(new Bitmap(Image.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("Paket.VisualStudio.Resources.NuGet.ico"))));
     Int32Rect sourceRect = new Int32Rect(0, 0, 16, 16);
     ImageSource imageSource = new CroppedBitmap(source, sourceRect);
     imageSource.Freeze();
     return imageSource;
 }
 public void BeginRender()
 {
     lock (_lockObj)
     {
         _bitmap.Lock();
         _updateRegion = new Int32Rect();
     }
 }
 internal void Show(Int32Rect rect)
 {
     Left = rect.X;
     Top = rect.Y;
     Width = rect.Width;
     Height = rect.Height;
     Show();
 }
Example #38
0
 private static Bitmap CropPortraitPicture(Bitmap picture, ushort maxdimension)
 {
     using (picture)
     {
         Int32Rect converted_crop = new System.Windows.Int32Rect();
         converted_crop.X = 0;
         converted_crop.Y = (picture.Height - maxdimension) / 2;;
         Rectangle crop_box = new Rectangle(converted_crop.X, converted_crop.Y, maxdimension, maxdimension);
         return(picture.Clone(crop_box, picture.PixelFormat));
     }
 }
Example #39
0
        public void AddMedia(BitmapSource bitmap)
        {
            System.Windows.Int32Rect rect;
            if (bitmap.PixelHeight > bitmap.PixelWidth * propotion)
            {
                rect = new System.Windows.Int32Rect(
                    0, (int)((bitmap.PixelHeight - bitmap.PixelWidth * propotion) / 2),
                    bitmap.PixelWidth, (int)(bitmap.PixelWidth * propotion)
                    );
            }
            else
            {
                rect = new System.Windows.Int32Rect(
                    (int)((bitmap.PixelHeight / propotion - bitmap.PixelHeight) / 2), 0,
                    (int)(bitmap.PixelHeight / propotion), bitmap.PixelHeight
                    );
            }

            CroppedBitmap cropped = null;

            try
            {
                cropped = new CroppedBitmap(bitmap, rect);
            }
            catch (ArgumentException e)
            {
                Console.Error.WriteLine("{0}, {1}", bitmap.PixelWidth, bitmap.PixelHeight);
                Console.Error.WriteLine(rect);
            }

            int count  = this.MediaPanel.Children.Count;
            int column = count % 2;
            int row    = count / 2;

            Image imageControl = new Image();

            imageControl.Source = cropped;
            Grid.SetColumn(imageControl, column);
            Grid.SetRow(imageControl, row);

            imageControl.MouseDown += (sender, e) =>
            {
                var mediaWindow = new MediaWindow();
                mediaWindow.MediaPanel.Children.Add(
                    new ZoomableImage()
                {
                    Source = bitmap
                });
                mediaWindow.Show();
            };

            this.MediaPanel.Children.Add(imageControl);
        }
Example #40
0
        public IconHandler(sd.Icon icon)
        {
            var rect = new sw.Int32Rect(0, 0, icon.Width, icon.Height);
            var img  = swi.Imaging.CreateBitmapSourceFromHIcon(icon.Handle, rect, swmi.BitmapSizeOptions.FromEmptyOptions());

            Control = swmi.BitmapFrame.Create(img);
            using (var ms = new MemoryStream())
            {
                icon.Save(ms);
                ms.Position = 0;
                SetFrames(ms);
            }
        }
Example #41
0
        // Load an image from disk for ROI drawing
        public void load_button_Click(object sender, RoutedEventArgs e)
        {
            var fname = "C:/Users/BehaveRig/Desktop/TM00000_CM0_CHN00-0083.tif";
            var img   = load_tif(fname, 0);

            image_base = new ushort[img.GetLength(0), img.GetLength(1)];
            image_base = (ushort[, ])img.Clone();

            var w = img.GetLength(1);
            var h = img.GetLength(0);

            bm = new WriteableBitmap(w, h, 96, 96, PixelFormats.Gray16, BitmapPalettes.Gray256);
            var rect   = new System.Windows.Int32Rect(0, 0, w, h);
            var stride = w * 2;

            bm.WritePixels(rect, img, stride, 0);
            image1.Width  = w / 3;
            image1.Height = h / 3;
            image1.Source = bm;
        }
Example #42
0
        public System.Windows.Media.Imaging.BitmapSource CaptureArea(System.Windows.Int32Rect rect)
        {
            // Initialize bitmap and pointers
            System.Windows.Media.Imaging.BitmapSource bitmapsource;

            Bitmap bmp   = null;
            IntPtr hDesk = IntPtr.Zero;
            IntPtr hSrce = IntPtr.Zero;
            IntPtr hDest = IntPtr.Zero;
            IntPtr hBmp  = IntPtr.Zero;

            try
            {
                hDesk = GetDesktopWindow();
                hSrce = GetWindowDC(hDesk);
                hDest = CreateCompatibleDC(hSrce);
                hBmp  = CreateCompatibleBitmap(hSrce, rect.Width, rect.Height);
                IntPtr hOldBmp = SelectObject(hDest, hBmp);
                bool   b       = BitBlt(hDest, 0, 0, rect.Width, rect.Height, hSrce, rect.X, rect.Y, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt);
                bmp = Bitmap.FromHbitmap(hBmp);

                // Create Bitmapsource from bitmap handle
                bitmapsource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    bmp.GetHbitmap(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()
                    );

                SelectObject(hDest, hOldBmp);
            }
            finally
            {
                DeleteObject(hBmp);
                DeleteDC(hDest);
                ReleaseDC(hDesk, hSrce);
                bmp.Dispose();
            }

            return(bitmapsource);
        }
 internal void CreateCameraViewWpfBitmapSource()
 {
     try
     {
         var capture = Device.CameraViewImageSourceBitmapCapture;
         var width   = capture.CameraViewImageSourceBitmapSize.Width;
         var height  = capture.CameraViewImageSourceBitmapSize.Height;
         Debug.Assert(width > 0 && height > 0);
         CameraViewWpfBitmapSource       = new System.Windows.Media.Imaging.WriteableBitmap(width, height, 96, 96, System.Windows.Media.PixelFormats.Bgr24, null);
         CameraViewWpfBitmapSourceWidth  = width;
         CameraViewWpfBitmapSourceHeight = height;
         CameraViewWpfBitmapSourceWritePixelsSourceRect = new System.Windows.Int32Rect(0, 0, width, height);
     }
     catch (Exception ex)
     {
         if (ApplicationCommonSettings.IsDebugging)
         {
             Debugger.Break();
         }
         Debug.WriteLine(ex.Message);
     }
 }
Example #44
0
        public void AppendData(float[] xVals, float[] yVals, int traceNum, ref WriteableBitmap bitmap)
        {
            try
            {
                // add new points to charts, update the charts, and redraw to screen

                GCHandle pinnedArray1 = GCHandle.Alloc(xVals, GCHandleType.Pinned);
                IntPtr   ptr1         = pinnedArray1.AddrOfPinnedObject();
                Marshal.Copy(xVals, 0, ptr1, xVals.Length);

                GCHandle pinnedArray2 = GCHandle.Alloc(yVals, GCHandleType.Pinned);
                IntPtr   ptr2         = pinnedArray2.AddrOfPinnedObject();
                Marshal.Copy(yVals, 0, ptr2, yVals.Length);

                ChartArray_AppendData(chartArray, ptr1, ptr2, xVals.Length, traceNum);

                IntPtr ptr = ChartArray_GetChartImagePtr(chartArray);

                if (ptr != IntPtr.Zero)
                {
                    int width  = (int)bitmap.Width;
                    int height = (int)bitmap.Height;

                    System.Windows.Int32Rect rect = new System.Windows.Int32Rect(0, 0, width, height);

                    bitmap.Lock();
                    bitmap.WritePixels(rect, ptr, width * height * 4, width * 4);
                    bitmap.Unlock();
                }

                pinnedArray1.Free();
                pinnedArray2.Free();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Marshaling Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #45
0
        private void Snap(object arg)
        {
            object[] argarr = arg as object[];
            IEnumerable <IBoundingBox> tosnap = argarr[0] as IEnumerable <IBoundingBox>;
            int index = (int)argarr[1];

            List <IBoundingBox> allsnapped = new List <IBoundingBox>();


            Bitmap tocrop = Bitmap.FromSystemDrawingBitmap(GetBitmap(index));

            foreach (IBoundingBox rect in tosnap)
            {
                System.Windows.Int32Rect snapped = RectangleFinder.SnapRect(Bitmap.Crop(tocrop, rect));
                BoundingBox snappedbb            = new BoundingBox(snapped.X + rect.Left + 1, snapped.Y + rect.Top + 1, snapped.Width, snapped.Height);
                allsnapped.Add(snappedbb);
            }

            if (RectsSnapped != null)
            {
                RectsSnapped(this, new RectsSnappedArgs(allsnapped));
            }
        }
Example #46
0
        public Sprite(string name, int width, int height, int numImages, int animSpeed)
        {
            spriteHeight   = height;
            spriteWidth    = width;
            numSheetImages = numImages;
            sheetName      = name;
            //this.Source = new BitmapImage(new Uri("/Locomotion;component/Media/Sprites/" + name + ".png", UriKind.Relative));
            Debug.Write("Sprite created.\n");


            if (numImages > 1)
            {
                BitmapImage spriteSheet = new BitmapImage(new Uri("/Locomotion;component/Media/Sprites/" + name + ".png", UriKind.Relative));
                spriteSheet.BaseUri = BaseUriHelper.GetBaseUri(this);

                croppedImages = new CroppedBitmap[numImages];

                for (int i = 0; i < numImages; i++)
                {
                    System.Windows.Int32Rect cropWindow = new System.Windows.Int32Rect(spriteWidth * i, 0, spriteWidth, spriteHeight);
                    croppedImages[i] = new CroppedBitmap(spriteSheet, cropWindow);
                }

                this.Source = croppedImages[0];
                currentFrame++;

                animationTimer.Interval = animSpeed;
                animationTimer.Tick    += new EventHandler(animationTimer_Tick);

                animationTimer.Start();
            }
            else
            {
                this.Source = new BitmapImage(new Uri("/Locomotion;component/Media/Graphics/" + name + ".png", UriKind.Relative));
                this.StopAnimation();
            }
        }
        private void Button_Crop_Click(object sender, RoutedEventArgs e)
        {
            if (Image_Previewer.Source != null)
            {
                double iX        = Image_Previewer.Width;
                double iY        = Image_Previewer.Height;
                double pX        = Image_Previewer.Source.Width;
                double pY        = Image_Previewer.Source.Height;
                double letterbox = (iY - pY) / 2;
                double pillarbox = (iX - pX) / 2;

                Rect rect1 = new Rect(Canvas.GetLeft(selectionRectangle), Canvas.GetTop(selectionRectangle), selectionRectangle.Width, selectionRectangle.Height);
                System.Windows.Int32Rect rcFrom = new System.Windows.Int32Rect();
                rcFrom.X      = (int)((rect1.X) /* - pillarbox */);
                rcFrom.Y      = (int)((rect1.Y) /* - letterbox */);
                rcFrom.Width  = (int)((rect1.Width) /* * (Image_Previewer.Source.Width) / (Image_Previewer.Width) */);
                rcFrom.Height = rcFrom.Width;
                BitmapSource bs = new CroppedBitmap(Image_Previewer.Source as BitmapSource, rcFrom);

                SaveImage(image: bs);

                Button_DeviceChooser_Click(sender, e);
            }
        }
Example #48
0
 public static bool Equals(Int32Rect int32Rect1, Int32Rect int32Rect2)
 {
     return(int32Rect1.Equals(int32Rect2));
 }
Example #49
0
        private bool CreateLayeredWindowFromImgBuffer(IntPtr pImgBuffer, long cImgBufferLen, bool topMost)
        {
            bool   bSuccess        = false;
            IntPtr pImagingFactory = IntPtr.Zero;
            IntPtr pDecoder        = IntPtr.Zero;
            IntPtr pIStream        = IntPtr.Zero;
            IntPtr pDecodedFrame   = IntPtr.Zero;
            IntPtr pBitmapSourceFormatConverter = IntPtr.Zero;
            IntPtr pBitmapFlipRotator           = IntPtr.Zero;

            try
            {
                UnsafeNativeMethods.HRESULT.Check(
                    UnsafeNativeMethods.WIC.CreateImagingFactory(UnsafeNativeMethods.WIC.WINCODEC_SDK_VERSION, out pImagingFactory));

                // Use the WIC stream class to wrap the unmanaged pointer
                UnsafeNativeMethods.HRESULT.Check(
                    UnsafeNativeMethods.WIC.CreateStream(pImagingFactory, out pIStream));

                UnsafeNativeMethods.HRESULT.Check(
                    UnsafeNativeMethods.WIC.InitializeStreamFromMemory(pIStream, pImgBuffer, (uint)cImgBufferLen));

                // Create an object that will decode the encoded image
                Guid vendor = Guid.Empty;
                UnsafeNativeMethods.HRESULT.Check(
                    UnsafeNativeMethods.WIC.CreateDecoderFromStream(pImagingFactory, pIStream,
                                                                    ref vendor, 0, out pDecoder));

                // Get the frame from the decoder. Most image formats have only a single frame, in the case
                // of animated gifs we are ok with only displaying the first frame of the animation.
                UnsafeNativeMethods.HRESULT.Check(
                    UnsafeNativeMethods.WIC.GetFrame(pDecoder, 0, out pDecodedFrame));

                UnsafeNativeMethods.HRESULT.Check(
                    UnsafeNativeMethods.WIC.CreateFormatConverter(pImagingFactory, out pBitmapSourceFormatConverter));

                // Convert the image from whatever format it is in to 32bpp premultiplied alpha BGRA
                Guid pixelFormat = UnsafeNativeMethods.WIC.WICPixelFormat32bppPBGRA;
                UnsafeNativeMethods.HRESULT.Check(
                    UnsafeNativeMethods.WIC.InitializeFormatConverter(pBitmapSourceFormatConverter, pDecodedFrame,
                                                                      ref pixelFormat, 0 /*DitherTypeNone*/, IntPtr.Zero,
                                                                      0, UnsafeNativeMethods.WIC.WICPaletteType.WICPaletteTypeCustom));
                // Reorient the image
                UnsafeNativeMethods.HRESULT.Check(
                    UnsafeNativeMethods.WIC.CreateBitmapFlipRotator(pImagingFactory, out pBitmapFlipRotator));

                UnsafeNativeMethods.HRESULT.Check(
                    UnsafeNativeMethods.WIC.InitializeBitmapFlipRotator(pBitmapFlipRotator, pBitmapSourceFormatConverter,
                                                                        UnsafeNativeMethods.WIC.WICBitmapTransformOptions.WICBitmapTransformFlipVertical));
                Int32 width, height;
                UnsafeNativeMethods.HRESULT.Check(
                    UnsafeNativeMethods.WIC.GetBitmapSize(pBitmapFlipRotator, out width, out height));

                Int32 stride = width * 4;

                // initialize the bitmap header
                MS.Win32.NativeMethods.BITMAPINFO bmInfo = new MS.Win32.NativeMethods.BITMAPINFO(width, height, 32 /*bpp*/);
                bmInfo.bmiHeader_biCompression = MS.Win32.NativeMethods.BI_RGB;
                bmInfo.bmiHeader_biSizeImage   = (int)(stride * height);

                // Create a 32bpp DIB.  This DIB must have an alpha channel for UpdateLayeredWindow to succeed.
                IntPtr pBitmapBits = IntPtr.Zero;
                _hBitmap = UnsafeNativeMethods.CreateDIBSection(new HandleRef(), ref bmInfo, 0 /* DIB_RGB_COLORS*/, ref pBitmapBits, null, 0);

                // Copy the decoded image to the new buffer which backs the HBITMAP
                Int32Rect rect = new Int32Rect(0, 0, width, height);
                UnsafeNativeMethods.HRESULT.Check(
                    UnsafeNativeMethods.WIC.CopyPixels(pBitmapFlipRotator, ref rect, stride, stride * height, pBitmapBits));

                _hwnd = CreateWindow(_hBitmap, width, height, topMost);

                bSuccess = true;
            }
            finally
            {
                if (pImagingFactory != IntPtr.Zero)
                {
                    Marshal.Release(pImagingFactory);
                }
                if (pDecoder != IntPtr.Zero)
                {
                    Marshal.Release(pDecoder);
                }
                if (pIStream != IntPtr.Zero)
                {
                    Marshal.Release(pIStream);
                }
                if (pDecodedFrame != IntPtr.Zero)
                {
                    Marshal.Release(pDecodedFrame);
                }
                if (pBitmapSourceFormatConverter != IntPtr.Zero)
                {
                    Marshal.Release(pBitmapSourceFormatConverter);
                }
                if (pBitmapFlipRotator != IntPtr.Zero)
                {
                    Marshal.Release(pBitmapFlipRotator);
                }

                if (bSuccess == false)
                {
                    DestroyResources(); // cleans up _hwnd and _hBitmap
                }
            }

            return(bSuccess);
        }
        private void InitialiseSpriteSheet(string tileSheetPath, int spriteSheetIdx)
        {
            // Initialise the appropriate sprite sheet
            if (spriteSheetIdx == 0)
            {
                _ListView_TileSet.Items.Clear();
            }
            else if (spriteSheetIdx == 1)
            {
                _Enemies_TileSheet.Items.Clear();
            }
            else if (spriteSheetIdx == 2)
            {
                _Other_Tilesheet.Items.Clear();
            }

            _spriteSheets[spriteSheetIdx].Clear();

            if (!System.IO.File.Exists(tileSheetPath))
            {
                return;
            }

            // Get the spriteSheet from the path
            BitmapSource tileSet = new BitmapImage(new Uri(@tileSheetPath, UriKind.RelativeOrAbsolute));

            for (int y = 0; y + _level.tileWidth <= tileSet.PixelHeight; y += _level.tileWidth)
            {
                for (int x = 0; x + _level.tileWidth <= tileSet.PixelWidth; x += _level.tileWidth)
                {
                    // Divide the sprite sheet into tiles
                    System.Windows.Int32Rect rect = new System.Windows.Int32Rect(x, y, _level.tileWidth, _level.tileWidth);
                    CroppedBitmap            cb   = new CroppedBitmap(tileSet, rect);

                    _spriteSheets[spriteSheetIdx].Add(cb);

                    // Create the sprite image
                    Image newImg = new Image();
                    newImg.Source = cb;
                    newImg.Width  = _tileRenderXY;
                    newImg.Height = _tileRenderXY;

                    // Add it to the appropriate sprite/tile sheet tab
                    if (spriteSheetIdx == 0)
                    {
                        _ListView_TileSet.Items.Add(newImg);
                    }
                    else if (spriteSheetIdx == 1)
                    {
                        _Enemies_TileSheet.Items.Add(newImg);
                    }
                    else if (spriteSheetIdx == 2)
                    {
                        _Other_Tilesheet.Items.Add(newImg);
                    }
                }
            }


            if (_ListView_TileSet.Items.Count > 0)
            {
                _ListView_TileSet.SelectedIndex = 0;
            }
            else if (_Enemies_TileSheet.Items.Count > 0)
            {
                _Enemies_TileSheet.SelectedIndex = 0;
            }
            else if (_Other_Tilesheet.Items.Count > 0)
            {
                _Other_Tilesheet.SelectedIndex = 0;
            }
        }