예제 #1
0
        public bool Create(Guid cameraGuid)
        {
            int w = 0, h = 0;

            _camera = CLEyeCreateCamera(cameraGuid, ColorMode, Resolution, Framerate);
            if (_camera == IntPtr.Zero)
            {
                return(false);
            }
            CLEyeCameraGetFrameDimensions(_camera, ref w, ref h);
            if (ColorMode == CLEyeCameraColorMode.CLEYE_COLOR_PROCESSED || ColorMode == CLEyeCameraColorMode.CLEYE_COLOR_RAW)
            {
                uint imageSize = (uint)w * (uint)h * 4;
                // create memory section and map
                _section     = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, imageSize, null);
                _map         = MapViewOfFile(_section, 0xF001F, 0, 0, imageSize);
                BitmapSource = Imaging.CreateBitmapSourceFromMemorySection(_section, w, h, PixelFormats.Bgr32, w * 4, 0) as InteropBitmap;
            }
            else
            {
                uint imageSize = (uint)w * (uint)h;
                // create memory section and map
                _section     = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, imageSize, null);
                _map         = MapViewOfFile(_section, 0xF001F, 0, 0, imageSize);
                BitmapSource = Imaging.CreateBitmapSourceFromMemorySection(_section, w, h, PixelFormats.Gray8, w, 0) as InteropBitmap;
            }
            // Invoke event
            if (BitmapReady != null)
            {
                BitmapReady(this, null);
            }
            BitmapSource.Invalidate();
            return(true);
        }
예제 #2
0
        protected void Initialize()
        {
            if (IsBitmapInitialized || IsBitmapInvalid)
            {
                Deallocate();
            }

            // this additional copy may not be necessary, but i want to keep using a local variable, and i don't want to access this.ActualWidth from this thread.
            var actualWidth  = ImageWidth;
            var actualHeight = ImageHeight;

            // but at least 1 pixel to avoid problems.
            actualHeight = Math.Max(1, actualHeight);
            actualWidth  = Math.Max(1, actualWidth);

            var byteCount = (uint)(actualWidth * actualHeight * BytesPerPixel);

            // Make memory map
            MapFileHandle = NativeMethods.CreateFileMapping(new IntPtr(-1), IntPtr.Zero, PAGE_READWRITE, 0, byteCount, null);
            MapViewPtr    = NativeMethods.MapViewOfFile(MapFileHandle, FILE_MAP_ALL_ACCESS, 0, 0, byteCount);

            //Create the InteropBitmap
            InteropBitmap = Imaging.CreateBitmapSourceFromMemorySection(MapFileHandle,
                                                                        actualWidth,
                                                                        actualHeight,
                                                                        PixelFormat,
                                                                        actualWidth * PixelFormat.BitsPerPixel / 8,
                                                                        0)
                            as InteropBitmap;
            GdiGraphics = GetGdiGraphics(MapViewPtr);

            IsBitmapInitialized = true;
            IsBitmapInvalid     = false;
        }
예제 #3
0
        public WpfNesVideoOut()
        {
            m_bitmapFileMapping = CreateFileMapping(
                new IntPtr(-1),
                IntPtr.Zero,
                0x04, //PAGE_READWRITE
                0,
                PixelCount * 4,
                null);

            unsafe
            {
                m_bitmapFileView = (int *)MapViewOfFile(
                    m_bitmapFileMapping,
                    0xF001F, //FILE_MAP_ALL_ACCESS
                    0,
                    0,
                    PixelCount * 4).ToPointer();
            }

            m_bitmapSource = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(
                m_bitmapFileMapping,
                ScreenWidth,
                ScreenHeight,
                PixelFormats.Bgr32,
                (ScreenWidth * PixelFormats.Bgr32.BitsPerPixel) / 8,
                0);
        }
예제 #4
0
        /// <summary>
        /// This kicks off the rendering thread.
        /// </summary>
        private void StartBevGeneration()
        {
            // If we are already rendering, then stop.
            StopBevRendering();

            _maxColumn = Entities.Max(e => (e.AlignedData != null) ? e.AlignedData.Count : 0);

            uint numPixels = (uint)(_maxColumn * Entities.Count);

            _section = CreateFileMapping(INVALID_HANDLE_VALUE, IntPtr.Zero, PAGE_READWRITE, 0, numPixels * 4, null);
            unsafe
            {
                _view = (int *)MapViewOfFile(_section, FILE_MAP_ALL_ACCESS, 0, 0, numPixels * 4).ToPointer();
                Parallel.For(0, numPixels, i => _view[i] = _whiteBlock);
            }

            _stride = (_maxColumn * PixelFormats.Bgr32.BitsPerPixel + 7) / 8;
            _bitmap = Imaging.CreateBitmapSourceFromMemorySection(_section, _maxColumn, Entities.Count, PixelFormats.Bgr32, _stride, 0) as InteropBitmap;

            OnPropertyChanged("BevImage");

            // No entities?  We're done.
            if (Entities == null)
            {
                return;
            }

            _stopFlag = false;
            _thread   = new Thread(GenerateBevImage)
            {
                Name = "Bev Generator", IsBackground = false, Priority = ThreadPriority.BelowNormal
            };
            _thread.Start();
        }
예제 #5
0
        // http://www.ipentec.com/document/document.aspx?page=csharp-wpf-screen-capture-sendkey-winform
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            //アクティブウィンドウをスクリーンキャプチャする場合
            System.Windows.Forms.SendKeys.SendWait("%{PRTSC}");

            //全画面をスクリーンキャプチャする場合
            //System.Windows.Forms.SendKeys.SendWait( "^{PRTSC}" );

            //全画面をスクリーンキャプチャする場合(こっち?)
            //System.Windows.Forms.SendKeys.SendWait( "{PRTSC}" );

            IDataObject dobj = Clipboard.GetDataObject();

            if (dobj.GetDataPresent(DataFormats.Bitmap) == true)
            {
                InteropBitmap ibmp = (InteropBitmap)dobj.GetData(DataFormats.Bitmap);

                BmpBitmapEncoder enc = new BmpBitmapEncoder();
                //JpegBitmapEncoder enc = new JpegBitmapEncoder();//JPEGファイルで保存する場合
                enc.Frames.Add(BitmapFrame.Create(ibmp));
                using (FileStream fs = new FileStream(@"screen2.bmp", FileMode.Create, FileAccess.Write)) {
                    enc.Save(fs);
                }
            }
        }
예제 #6
0
 public OpenCvTest()
 {
     InitializeComponent();
     _ipcImage       = IpcImageFileMapped.LoadFromFile(ImageUris.LargeBitmapBgr);
     _interopBitmap  = _ipcImage.GetInteropBitmap();
     ImageWpf.Source = _interopBitmap;
 }
예제 #7
0
        public bool StartStream(string url)
        {
            ///Оборачиваем конструктор класса VideoCapture в задачу, и ждем завершения 5 секунд.
            ///Это необходимо, т.к. у VideoCapture нет таймаута и если камера не ответила, то приложение зависнет.
            var CaptureTask = Task.Factory.StartNew(() => Capture = new VideoCapture(url));

            if (!CaptureTask.Wait(new TimeSpan(0, 0, 5)))
            {
                return(false);
            }
            ///Получаем первый кадр с камеры
            Capture.Grab();
            ///Если удачно записали его в переменную, то продолжаем
            if (!Capture.Retrieve(MatFrame, 3))
            {
                return(false);
            }
            ///Узнаем формат пикселей кадра
            System.Windows.Media.PixelFormat pixelFormat = GetPixelFormat(MatFrame);
            ///Определяем сколько места занимает один кадр
            pcount = (uint)(MatFrame.Width * MatFrame.Height * pixelFormat.BitsPerPixel / 8);
            ///Создаем объект в памяти
            source = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, pcount, null);
            ///Получаем ссылку на начальный адрес объекта
            map = MapViewOfFile(source, 0xF001F, 0, 0, pcount);
            ///Инициализируем InteropBitmap используя созданный выше объект в памяти
            Frame = Imaging.CreateBitmapSourceFromMemorySection(source, MatFrame.Width, MatFrame.Height, pixelFormat, MatFrame.Width * pixelFormat.BitsPerPixel / 8, 0) as InteropBitmap;
            Capture.ImageGrabbed += Capture_ImageGrabbed;
            Capture.Start();
            return(true);
        }
예제 #8
0
        private void Cleanup()
        {
            this.source = null;
            if (this.refreshThread != null)
            {
                this.refreshThread.Join();
                this.refreshThread = null;
            }

            if (this.readyEvent != null)
            {
                this.readyEvent.Dispose();
                this.readyEvent = null;
            }

            if (this.view != null)
            {
                this.view.Dispose();
                this.view = null;
            }

            if (this.sharedMemory != null)
            {
                this.sharedMemory.Dispose();
                this.sharedMemory = null;
            }
        }
예제 #9
0
        public override void Perform()
        {
            InteropBitmap bitmap = (InteropBitmap)TargetImage.Source;

            // clamp to valid ranges
            DrawRect = Clamp(bitmap, DrawRect);
            SafeFileHandle sectionHandle = (SafeFileHandle)bitmap.GetValue(InteropBitmapFactory.HandleProperty);

            if (sectionHandle == null || sectionHandle.IsInvalid)
            {
                throw new InvalidOperationException("Handle property not set on the InteropBitmap");
            }

            int  bytesPerPixel     = (int)((bitmap.Format.BitsPerPixel + 7.0) / 8.0);
            uint bufferSizeInBytes = (uint)(bitmap.PixelWidth * bitmap.PixelHeight * bytesPerPixel);

            unsafe
            {
                IntPtr viewHandle = InteropBitmapFactory.MapViewOfFile(sectionHandle.DangerousGetHandle(), InteropBitmapFactory.FILE_MAP_ALL_ACCESS, 0, 0, bufferSizeInBytes);

                byte *pixels = (byte *)viewHandle.ToPointer();

                DrawToBitmap(pixels, bitmap);
                bitmap.Invalidate();

                InteropBitmapFactory.UnmapViewOfFile(viewHandle);
            }
        }
예제 #10
0
        /// <summary>
        /// 图片绑定
        /// </summary>
        /// <returns></returns>
        public static IntPtr BindingBitmap(ref InteropBitmap interopBitmap, IntPtr map, Bitmap bitmap)
        {
            if (bitmap == null)
            {
                return(map);
            }
            if (interopBitmap == null)
            {
                //创建内存映射
                uint   pcount  = (uint)(bitmap.Width * bitmap.Height * System.Windows.Media.PixelFormats.Bgr32.BitsPerPixel / 8.0);
                IntPtr section = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, pcount, null);
                map           = MapViewOfFile(section, 0xF001F, 0, 0, pcount);
                interopBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromMemorySection(section, (int)bitmap.Width, (int)bitmap.Height, System.Windows.Media.PixelFormats.Bgr32,
                                                                                                   (int)(bitmap.Width * System.Windows.Media.PixelFormats.Bgr32.BitsPerPixel / 8), 0) as InteropBitmap;
            }
            System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, (int)bitmap.Width, (int)bitmap.Height),
                                                                        System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            /* Get the pointer to the pixels */
            IntPtr pBmp      = bmpData.Scan0;
            int    srcStride = bmpData.Stride;
            int    pSize     = srcStride * (int)bitmap.Height;

            CopyMemory(map, pBmp, pSize);
            bitmap.UnlockBits(bmpData);
            if (interopBitmap != null)
            {
                interopBitmap.Invalidate();
            }
            return(map);
        }
예제 #11
0
 public InteropGdi()
 {
     InitializeComponent();
     _ipcImage       = IpcImageFileMapped.LoadFromFile(ImageUris.LargeBitmapBgr);
     _interopBitmap  = _ipcImage.GetInteropBitmap();
     ImageWpf.Source = _interopBitmap;
     DrawGdiImage(null, null);
 }
        public void CameraDataUpdate(InteropBitmap cameraInterop)
        {
            // Stores the cam input as bitmap source
            var imageSource = cameraInterop as BitmapSource;

            // Creates an jpeg encoder
            BitmapEncoder enc = new JpegBitmapEncoder();

            // Create bitmap frame from the image source
            enc.Frames.Add(BitmapFrame.Create(imageSource));

            // Saves the frame to a memory stream
            var ms = new MemoryStream();

            enc.Save(ms);

            // Create a bitmap from the memory stream
            var bitmap = new Bitmap(ms);

            // Get width and height
            int width  = bitmap.Width;
            int height = bitmap.Height;

            // Gets the buffer from the texture
            var texBuffer = m_texture.GetBuffer();

            // Locks the buffer so we can copy data into the buffer
            texBuffer.Lock(BufferLocking.Discard);
            PixelBox   pb   = texBuffer.CurrentLock;
            BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, width, height),
                                              ImageLockMode.ReadOnly,
                                              System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            // Copy the data into the buffer
            CopyMemory(pb.Data, data.Scan0, (uint)((width) * height * 4));

            // Unlock the buffer
            bitmap.UnlockBits(data);
            texBuffer.Unlock();

            // Render using the material
            m_axiomMaterial.GetTechnique(0).GetPass(0).RemoveAllTextureUnitStates();
            m_axiomMaterial.GetTechnique(0).GetPass(0).CreateTextureUnitState("DynamicTexture");

            // Update the camera orientation
            UpdateCameraOrientation();

            try
            {
                // Render a single frame
                m_root.RenderOneFrame();
            }
            catch (Exception e)
            {
                return;
            }
        }
예제 #13
0
        /// <summary>
        /// 打开摄像头
        /// </summary>
        public override void OpenDevice(string deviceName)
        {
            base.OpenDevice(deviceName);
            //创建内存映射
            width  = ActualResolution.Width;
            height = ActualResolution.Height;
            uint pcount = (uint)(this.width * this.height * PixelFormats.Bgr32.BitsPerPixel / 8.0);

            section           = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, pcount, null);
            map               = MapViewOfFile(section, 0xF001F, 0, 0, pcount);
            FrameBitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromMemorySection(section, (int)this.width, (int)this.height, PixelFormats.Bgr32,
                                                                                                   (int)(this.width * PixelFormats.Bgr32.BitsPerPixel / 8), 0) as InteropBitmap;
        }
예제 #14
0
        public bool Open()
        {
            if (this.view != null)
            {
                return(false);
            }

            try
            {
                this.readyEvent   = EventWaitHandle.OpenExisting(ReadyEventName);
                this.sharedMemory = MemoryMappedFile.OpenExisting(SharedMemoryName, MemoryMappedFileRights.Read);
                this.view         = this.sharedMemory.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                this.Cleanup();
                return(false);
            }

            BITMAP bmp;

            this.view.Read(0, out bmp);
            var width         = bmp.bmWidth;
            var height        = bmp.bmHeight;
            var pixelFormat   = PixelFormats.Gray8;
            var bytesPerPixel = (pixelFormat.BitsPerPixel + 7) / 8;
            var stride        = bytesPerPixel * width;

            var shmemPtr = this.sharedMemory.SafeMemoryMappedFileHandle.DangerousGetHandle();

            this.source = Imaging.CreateBitmapSourceFromMemorySection(
                shmemPtr,
                width,
                height,
                pixelFormat,
                stride,
                bmp.bmBits.ToInt32()) as InteropBitmap;
            if (this.source == null)
            {
                const string ErrorMessage = "Unexpected type from CreateBitmapSourceFromMemorySection.";
                Debug.Fail(ErrorMessage);
                Debug.WriteLine(ErrorMessage);
                this.Cleanup();
                return(false);
            }

            this.refreshThread = new Thread(this.RefreshThread);
            this.refreshThread.Start();
            return(true);
        }
예제 #15
0
        public WriteableBitmap(IntPtr intPtr, int width, int height, PixelFormat pixelFormat)
        {
            Width         = width;
            Height        = height;
            PixelFormat   = pixelFormat;
            Stride        = CalculateStride(pixelFormat, width);
            Offset        = 0;
            BytesPerPixel = ((pixelFormat.BitsPerPixel + 7) / 8);
            Length        = width * height * BytesPerPixel;

            _memoryMapSection = intPtr;

            _mapView            = Win32Interop.MapViewOfFile(_memoryMapSection, 0xF001F, 0, 0, (UInt32)Length);
            _mustDisposeMapView = true;

            BitmapSource = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(_mapView, width, height, pixelFormat, Stride, Offset);
        }
예제 #16
0
        private BitmapSource RenderControl(WinForms.Control control)
        {
            if (control == null || control.Width == 0 || control.Height == 0)
            {
                return(null);
            }

            if (Buffer == null || Buffer.Width < control.Width || Buffer.Height < control.Height)
            {
                var dpi = DisplayInfo.FromPresentationSource(PresentationSource.FromVisual(Image));
                Buffer = new InteropBitmap(control.Width, control.Height, (float)dpi.DpiX, (float)dpi.DpiY, InteropBitmapFormat.Rgba32);
            }

            Buffer.Render(target => control.DrawToBitmap(target, control.Bounds));

            return(Buffer.Bitmap);
        }
예제 #17
0
        private object SetBitmapHelper(BitmapInfo bitmapInfo, InteropBitmap bitmap, Action <InteropBitmap> imageSourceSetter)
        {
            if (bitmap == null)
            {
                imageSourceSetter(null);
                GC.Collect(1);

                var stride = bitmapInfo.Width * ((IRenderWebBrowser)this).BytesPerPixel;

                bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(bitmapInfo.FileMappingHandle,
                                                                                    bitmapInfo.Width, bitmapInfo.Height, PixelFormat, stride, 0);
                imageSourceSetter(bitmap);
            }

            bitmap.Invalidate();

            return(bitmap);
        }
예제 #18
0
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        internal void Initialize()
        {
#if WPF && !PUPLISH
            if (ActualHeight > 1 && ActualWidth > 1)
            {
                switch (RenderingMode)
                {
                case RenderingMode.GDIRendering:
                    uint byteCount = (uint)(ActualWidth * ActualHeight * bpp);

                    //Allocate and create the InteropBitmap
                    var fileMappingPointer = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, PageReadwrite, 0, byteCount, null);
                    this.MapViewPointer = MapViewOfFile(fileMappingPointer, FileMapAllAccess, 0, 0, byteCount);
                    var format = PixelFormats.Bgra32;
                    var stride = (int)((int)ActualWidth * (int)format.BitsPerPixel / 8);
                    this.InteropBitmap = Imaging.CreateBitmapSourceFromMemorySection(fileMappingPointer,
                                                                                     (int)ActualWidth,
                                                                                     (int)ActualHeight,
                                                                                     format,
                                                                                     stride,
                                                                                     0) as InteropBitmap;
                    this.GDIGraphics = GetGdiGraphics(MapViewPointer);
                    break;

                case RenderingMode.WritableBitmap:
                    //Allocate and create the WritableBitmap
                    WritableBitmap         = new WriteableBitmap((int)ActualWidth, (int)ActualHeight, 96, 96, PixelFormats.Bgra32, null);
                    ImageBitmap            = new Bitmap((int)ActualWidth, (int)ActualHeight, ((int)ActualWidth * 4), System.Drawing.Imaging.PixelFormat.Format32bppPArgb, WritableBitmap.BackBuffer);
                    WritableBitmapGraphics = System.Drawing.Graphics.FromImage(ImageBitmap);
                    WritableBitmapGraphics.CompositingMode    = this.CompositingMode.AsDrawingCompositingMode();
                    WritableBitmapGraphics.CompositingQuality = this.CompositingQuality.AsDrawingCompositingQuality();
                    WritableBitmapGraphics.SmoothingMode      = this.SmoothingMode.AsDrawingSmoothingMode();
                    break;

                default:
                    break;
                }

                Clear();
                this.IsBitmapInitialized = true;
            }
#endif
        }
예제 #19
0
            public void Render(ImageHost host)
            {
                lock (SyncLock)
                {
                    if (IsDisposed)
                    {
                        return;
                    }

                    if (NeedsNewImage)
                    {
                        BackBufferImage = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(
                            BackBufferFile.SafeMemoryMappedFileHandle.DangerousGetHandle(), Width, Height, PixelFormats.Bgra32, Stride, 0);

                        NeedsNewImage = false;
                    }

                    BackBufferImage.Invalidate();
                    host.Source = BackBufferImage;
                }
            }
예제 #20
0
        public WriteableBitmap(int width, int height, PixelFormat pixelFormat)
        {
            Width         = width;
            Height        = height;
            PixelFormat   = pixelFormat;
            Stride        = CalculateStride(pixelFormat, width);
            Offset        = 0;
            BytesPerPixel = ((pixelFormat.BitsPerPixel + 7) / 8);
            Length        = width * height * BytesPerPixel;

            //IntPtr = Marshal.AllocHGlobal(Length);
            //this.MemoryMappedFile = MemoryMappedFile.CreateNew(null, Length, MemoryMappedFileAccess.ReadWrite);
            //IntPtr = this.MemoryMappedFile.CreateViewAccessor().SafeMemoryMappedViewHandle.DangerousGetHandle();

            _memoryMapSection            = Win32Interop.CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, (UInt32)Length, null);
            _mustDisposeMemoryMapSection = true;
            _mapView            = Win32Interop.MapViewOfFile(_memoryMapSection, 0xF001F, 0, 0, (UInt32)Length);
            _mustDisposeMapView = true;

            BitmapSource = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(_memoryMapSection, width, height, pixelFormat, Stride, Offset);
        }
예제 #21
0
        public static Bitmap ConvertImageSourceToBitmap(this ImageSource source)
        {
            Bitmap result = null;

            InteropBitmap src = (InteropBitmap)source;

            int height = src.PixelHeight;

            int width = src.PixelWidth;

            int stride = width * ((src.Format.BitsPerPixel + 7) / 8);

            IntPtr prt = Marshal.AllocHGlobal(height * stride);

            try
            {
                src.CopyPixels(new Int32Rect(0, 0, width, height), prt, height * stride, stride);

                result = new Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format32bppArgb, prt);

                long handle = (long)result.GetHbitmap();

                GC.AddMemoryPressure(handle > 0 ? handle : handle * -1);
            }
            catch
            {
                throw;
            }
            finally
            {
                Marshal.Release(prt);

                src = null;

                source = null;
            }

            return(result);
        }
예제 #22
0
        private uint VideoSetFormat(ref IntPtr opaque, ref uint chroma, ref uint width, ref uint height, ref uint pitches, ref uint lines)
        {
            var context = new VlcControlWpfRendererContext(width, height, PixelFormats.Bgr32);

            chroma  = BitConverter.ToUInt32(new[] { (byte)'R', (byte)'V', (byte)'3', (byte)'2' }, 0);
            width   = (uint)context.Width;
            height  = (uint)context.Height;
            pitches = (uint)context.Stride;
            lines   = (uint)context.Height;

            myBitmapSectionPointer = Win32Interop.CreateFileMapping(new IntPtr(-1), IntPtr.Zero, Win32Interop.PageAccess.ReadWrite, 0, context.Size, null);
            opaque = Win32Interop.MapViewOfFile(myBitmapSectionPointer, Win32Interop.FileMapAccess.AllAccess, 0, 0, (uint)context.Size);

            Dispatcher.Invoke((Action)(() =>
            {
                myBitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(myBitmapSectionPointer, context.Width, context.Height, context.PixelFormat, context.Stride, 0);
                VideoSource = myBitmap;
                VideoBrush.ImageSource = myBitmap;
            }));

            return(1);
        }
예제 #23
0
private void DoDecoding(object state)
{
    this.Dispatcher.BeginInvoke((Action)(() =>
    {
        try
        {
            InteropBitmap bitmap = videoSin.SourceProvider.VideoSource as    InteropBitmap;
            if (bitmap != null)
            {
                var result = reader.Decode(bitmap);
                if (result != null)
                {
                    MessageBox.Show(result.Text);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
                                         ));
}
예제 #24
0
        public MemMappedBitmap(int width, int height)
        {
            if ((width < 1) || (width > MaxPixelsPerDimension))
            {
                throw new ArgumentOutOfRangeException("width");
            }
            if ((height < 1) || (height > MaxPixelsPerDimension))
            {
                throw new ArgumentOutOfRangeException("height");
            }

            section     = MemoryMappedFile.CreateNew(null, width * height * sizeof(uint));
            sectionView = section.CreateViewAccessor();
            byte *ptr = null;

            sectionView.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
            bgr32 = (uint *)ptr;

            Clear(bgr32, width * height);
            interop = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(
                section.SafeMemoryMappedFileHandle.DangerousGetHandle(), width, height,
                PixelFormats.Bgr32, width * sizeof(uint), 0);
        }
예제 #25
0
 private void VideoCleanup(IntPtr opaque)
 {
     myBitmap = null;
     Win32Interop.UnmapViewOfFile(opaque);
     Win32Interop.CloseHandle(myBitmapSectionPointer);
 }
        protected override void OnRender(DrawingContext dc)
        {
            base.OnRender(dc);
            if (Lines.Count() > 0)
            {
                ImageSource drIs = null;

                if (interopBitmap == null)
                {
                    uint byteCount = (uint)((int)this.ActualWidth * (int)this.ActualHeight * bpp);

                    var fileMappingPointer = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, PAGE_READWRITE, 0, byteCount, null);
                    this.MapViewPointer = MapViewOfFile(fileMappingPointer, FILE_MAP_ALL_ACCESS, 0, 0, byteCount);
                    PixelFormat format = PixelFormats.Bgra32;
                    var         stride = (int)((int)this.ActualWidth * format.BitsPerPixel / 8);
                    this.interopBitmap = Imaging.CreateBitmapSourceFromMemorySection(fileMappingPointer,
                                                                                     (int)this.ActualWidth,
                                                                                     (int)this.ActualHeight,
                                                                                     format,
                                                                                     stride,
                                                                                     0) as InteropBitmap;

                    this.GDIGraphics = GetGdiGraphics(MapViewPointer);
                }

                GDIGraphics.FillRectangle(System.Drawing.Brushes.Transparent,
                                          new System.Drawing.Rectangle(0, 0,
                                                                       (int)this.ActualWidth,
                                                                       (int)this.ActualHeight));

                foreach (ScopeLine dLine in Lines)
                {
                    var   pointCount = dLine.linePoints.Count();
                    Color lpColour;
                    lpColour = dLine.lineBrush.Color;
                    System.Drawing.Color lp2Colour;
                    lp2Colour = System.Drawing.Color.FromArgb(lpColour.A,
                                                              lpColour.R,
                                                              lpColour.G,
                                                              lpColour.B);


                    System.Drawing.Pen    lpPen    = new System.Drawing.Pen(lp2Colour, 1.5f);
                    System.Drawing.PointF newPoint = new System.Drawing.PointF((float)dLine.linePoints[0].X,
                                                                               (float)dLine.linePoints[0].Y);


                    for (int i = 0; i < pointCount - 1; i++)
                    {
                        System.Drawing.PointF newPoint1 = new System.Drawing.PointF((float)dLine.linePoints[i + 1].X,
                                                                                    (float)dLine.linePoints[i + 1].Y);
                        GDIGraphics.DrawLine(lpPen, newPoint, newPoint1);
                        newPoint = newPoint1;
                    }
                }

                var bmpsrc = interopBitmap.GetAsFrozen();
                if (bmpsrc == null || bmpsrc.CheckAccess())
                {
                    drIs = (System.Windows.Media.Imaging.BitmapSource)bmpsrc;
                }
                else
                {
                    //Debug.WriteLine("No access to TheImage");
                }

                dc.DrawImage(drIs, new Rect(this.RenderSize));
            }
        }
예제 #27
0
        internal void Refresh(bool invalidate)
        {
#if DIRECTX2D
            if (RenderingMode == RenderingMode.DirectX2D)
            {
                InitializeDirectX();
            }
#endif
            switch (RenderingMode)
            {
#if WPF
            case RenderingMode.GDIRendering:
                if (this.InteropBitmap != null && this.GDIGraphics != null)
                {
                    this.GDIGraphics.Dispose();
                    this.GDIGraphics   = null;
                    this.InteropBitmap = null;
                    GC.Collect();
                }
                break;

            case RenderingMode.WritableBitmap:
                if (this.WritableBitmap != null && this.WritableBitmapGraphics != null)
                {
                    this.WritableBitmapGraphics.Dispose();
                    this.WritableBitmapGraphics = null;
                    this.WritableBitmap         = null;
                    GC.Collect();
                }
                break;
#endif
            case RenderingMode.Default:
                break;

            default:
                break;
            }

            Initialize();
            if (!_isIntialized || invalidate)
            {
                GenerateConatiners();
            }
            else
            {
                UpdateContainers();
            }

            if (this.XAxis != null)
            {
                this.XAxis.MMinValue = 0;
                this.XAxis.MMaxValue = 1;
                this.XAxis.CalculateIntervalFromSeriesPoints();
                this.XAxis.Refresh();
            }
            if (this.YAxis != null)
            {
                this.YAxis.MMinValue = 0;
                this.YAxis.MMaxValue = 1;
                this.YAxis.CalculateIntervalFromSeriesPoints();
                this.YAxis.Refresh();
            }
            if (this.Series != null)
            {
                foreach (SeriesBase series in this.Series)
                {
                    if (Containers.Count > 0 && (this.Series.Count == Containers.Count))
                    {
                        series.SeriesContainer = Containers[series.Index];
                    }
                    series.Refresh();
                }
            }
        }
 public void UpdateBits(int[] pixelData)
 {
     Marshal.Copy(pixelData, 0, _ImageBits, ((int)_ColorByteCount) / sizeof(int));
     InteropBitmap.Invalidate();
 }
예제 #29
0
        public bool Create(Guid cameraGuid)
        {
            _camera = CLEyeCreateCamera(cameraGuid, ColorMode, Resolution, Framerate);
            if (_camera == IntPtr.Zero)
            {
                return(false);
            }
            CLEyeCameraGetFrameDimensions(_camera, ref width, ref height);
            if (ColorMode == CLEyeCameraColorMode.CLEYE_COLOR)
            {
                bufferLength = width * height * 4;
                // create memory section and map
                section      = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, (uint)bufferLength, "EyeVideo");
                map          = MapViewOfFile(section, 0xF001F, 0, 0, (uint)bufferLength);
                BitmapSource = Imaging.CreateBitmapSourceFromMemorySection(
                    section,
                    width,
                    height,
                    PixelFormats.Bgr32,
                    width * 4,
                    0) as InteropBitmap;
                this.stride     = width * ((BitmapSource.Format.BitsPerPixel + 7) / 8);
                this.colorFrame = new Emgu.CV.Image <Emgu.CV.Structure.Bgr, byte>(
                    this.width,
                    this.height,
                    this.stride,
                    map);
            }
            else
            {
                bufferLength = width * height;
                // create memory section and map
                section      = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, (uint)bufferLength, "EyeVideo");
                map          = MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, (uint)bufferLength);
                BitmapSource = Imaging.CreateBitmapSourceFromMemorySection(
                    section,
                    width,
                    height,
                    PixelFormats.Gray8,
                    width,
                    0) as InteropBitmap;
                this.stride    = width * ((BitmapSource.Format.BitsPerPixel + 7) / 8);
                this.grayFrame = new Emgu.CV.Image <Emgu.CV.Structure.Gray, byte>(
                    this.width,
                    this.height,
                    this.stride,
                    map);
            }

            // Invoke event
            if (BitmapReady != null)
            {
                BitmapReady(this, null);
            }

            BitmapSource.Invalidate();

            this.AutoExposure     = true;
            this.AutoGain         = true;
            this.AutoWhiteBalance = true;

            return(true);
        }
예제 #30
0
 public void UpdateBits(byte[] imageBits)
 {
     Marshal.Copy(imageBits, 0, _ImageBits, (int)_ColorByteCount);
     InteropBitmap.Invalidate();
 }