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); }
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); }
/// <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(); }
private void Browser_Paint(object sender, OnPaintEventArgs e) { var newbitmap = false; int pixels = e.Width * e.Height, numberOfBytes = pixels * BytesPerPixel; newbitmap = viewMemoryMappedFile == null || Height != e.Height || Width != e.Width; try { ReleaseMemoryMappedView(ref viewMemoryMappedFile, ref viewMemoryMappedViewAccessor); viewMemoryMappedFile = MemoryMappedFile.CreateNew(null, numberOfBytes, MemoryMappedFileAccess.ReadWrite); viewMemoryMappedViewAccessor = viewMemoryMappedFile.CreateViewAccessor(); CopyMemory(viewMemoryMappedViewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), e.BufferHandle, (uint)numberOfBytes); var backBufferHandle = viewMemoryMappedFile.SafeMemoryMappedFileHandle; if (backBufferHandle.IsClosed || backBufferHandle.IsInvalid) { return; } var stride = e.Width * BytesPerPixel; var bs = Imaging.CreateBitmapSourceFromMemorySection(backBufferHandle.DangerousGetHandle(), e.Width, e.Height, PixelFormat, stride, 0); Screenshot = new Bitmap(e.Width, e.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); System.Drawing.Imaging.BitmapData data = Screenshot.LockBits(new Rectangle(Point.Empty, Screenshot.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); bs.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); SetBitmap(Screenshot, this); GC.Collect(1); } catch { } }
private void SetResolution(uint bitmapWidth, uint bitmapHeight) { lock (updateLock) { if (map != IntPtr.Zero) { MemoryInternal.UnmapViewOfFile(map); map = IntPtr.Zero; } if (section != IntPtr.Zero) { MemoryInternal.CloseHandle(section); section = IntPtr.Zero; } uint imageSize = (uint)bitmapWidth * (uint)bitmapHeight; if (imageSize == 0x00) { return; } // create memory section and map section = MemoryInternal.CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, imageSize, null); map = MemoryInternal.MapViewOfFile(section, 0xF001F, 0, 0, imageSize); } Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, (SendOrPostCallback) delegate { Bitmap = Imaging.CreateBitmapSourceFromMemorySection(section, (int)bitmapWidth, (int)bitmapHeight, PixelFormats.Gray8, (int)bitmapWidth, 0) as InteropBitmap; Bitmap.Invalidate(); Source = Bitmap; Stretch = System.Windows.Media.Stretch.Fill; StretchDirection = StretchDirection.Both; }, null); }
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; }
void IRenderWebBrowser.InvokeRenderAsync(BitmapInfo bitmapInfo) { UiThreadRunAsync(delegate { lock (bitmapInfo.BitmapLock) { var interopBitmapInfo = (InteropBitmapInfo)bitmapInfo; // Inform parents that the browser rendering is updating OnRendering(this, interopBitmapInfo); // Now update the WPF image var bitmap = interopBitmapInfo.InteropBitmap; if (bitmap == null) { var img = bitmapInfo.IsPopup ? popupImage : image; img.Source = null; GC.Collect(1); var stride = bitmapInfo.Width * bitmapInfo.BytesPerPixel; bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(bitmapInfo.FileMappingHandle, bitmapInfo.Width, bitmapInfo.Height, PixelFormat, stride, 0); img.Source = bitmap; interopBitmapInfo.InteropBitmap = bitmap; } bitmap.Invalidate(); } }, DispatcherPriority.Render); }
void capGrabber_PropertyChanged(object sender, PropertyChangedEventArgs e) { Dispatcher.Invoke(DispatcherPriority.DataBind, (SendOrPostCallback) delegate { try { if (capGrabber.Width != default(int) && capGrabber.Height != default(int)) { //retrieves the pixel count uint pcount = (uint)(capGrabber.Width * capGrabber.Height * PixelFormats.Bgr32.BitsPerPixel / 8); //creates the intial file mapping section = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, pcount, null); map = MapViewOfFile(section, 0xF001F, 0, 0, pcount); //Gets the bitmap BitmapSource = Imaging.CreateBitmapSourceFromMemorySection(section, capGrabber.Width, capGrabber.Height, PixelFormats.Bgr32, capGrabber.Width * PixelFormats.Bgr32.BitsPerPixel / 8, 0) as InteropBitmap; capGrabber.Map = map; if (OnNewBitmapReady != null) { OnNewBitmapReady(this, null); } } } catch (Exception ex) { // Trace Trace.TraceError(ex.Message); } }, null); }
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); }
public unsafe BitmapSource GetOrUpdateBitmapSource() { if (_bitmapSourcePtr == null) { var stride = Width * 4; // Size of "horizontal row" var sectionSize = _sizeInBytes; var section = NativeMethods.CreateFileMapping(NativeMethods.INVALID_HANDLE_VALUE, IntPtr.Zero, (int)NativeMethods.PAGE_READWRITE, 0, (int)sectionSize, null); _bitmapSource = Imaging.CreateBitmapSourceFromMemorySection(section, (int)Width, (int)Height, PixelFormats.Bgr32, (int)stride, 0); _bitmapSourcePtr = (uint)NativeMethods.MapViewOfFile(section, NativeMethods.FILE_MAP_ALL_ACCESS, 0, 0, sectionSize).ToPointer(); NativeMethods.CloseHandle(section); NativeMethods.UnmapViewOfFile(section); // We can use mapped memory directly to draw, but I could not find a way to avoid flickering in this case. So we sprite memory as a double buffer. //var sectionSize = _sizeInBytes + SizeofSpriteHeader; //var section = NativeMethods.CreateFileMapping(NativeMethods.INVALID_HANDLE_VALUE, IntPtr.Zero, (int) NativeMethods.PAGE_READWRITE, 0, (int) sectionSize, null); //_bitmapSource = Imaging.CreateBitmapSourceFromMemorySection(section, (int)Width, (int)Height, PixelFormats.Bgr32, (int)stride, (int) SizeofSpriteHeader); //_bitmapSourcePtr = (uint)NativeMethods.MapViewOfFile(section, NativeMethods.FILE_MAP_ALL_ACCESS, 0, 0, sectionSize).ToPointer(); //NativeMethods.CloseHandle(section); //NativeMethods.UnmapViewOfFile(section); //TpsGraphWrapper.CopyMemory((uint) _bitmapSourcePtr, _dataPtr, _sizeInBytes + SizeofSpriteHeader); //TpsGraphWrapper.FreeSprite(_dataPtr); //_shouldFreeSprite = false; //_dataPtr = (uint)_bitmapSourcePtr; } CopyPixelsTo((uint)_bitmapSourcePtr); return(_bitmapSource); }
private void Initialize(int width, int height, Array pixelData, int bitsPerPixel, PixelFormat pixelFormat) { _Width = width; _Height = height; _PixelFormat = pixelFormat; int stride = width * ((bitsPerPixel + 7) / 8); _ColorByteCount = (uint)(height * stride); var colorFileMapping = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, _ColorByteCount, null); _ImageBits = MapViewOfFile(colorFileMapping, 0xF001F, 0, 0, _ColorByteCount); byte[] bytes = pixelData as byte[]; if (bytes != null) { Marshal.Copy(bytes, 0, _ImageBits, (int)_ColorByteCount); } else { int[] ints = pixelData as int[]; if (ints != null) { Marshal.Copy(ints, 0, _ImageBits, (int)_ColorByteCount / sizeof(int)); } } InteropBitmap = Imaging.CreateBitmapSourceFromMemorySection(colorFileMapping, width, height, _PixelFormat, stride, 0) as InteropBitmap; }
/// <summary> /// Invoked when a property of the CapGrabber object has changed /// </summary> /// <param name="sender">Sender</param> /// <param name="e">PropertyChangedEventArgs</param> private void capGrabber_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.DataBind, (SendOrPostCallback) delegate { try { if ((_capGrabber.Width != default(int)) && (_capGrabber.Height != default(int))) { // Get the pixel count uint pcount = (uint)(_capGrabber.Width * _capGrabber.Height * PixelFormats.Bgr32.BitsPerPixel / 8); // Create a file mapping _section = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, pcount, null); _map = MapViewOfFile(_section, 0xF001F, 0, 0, pcount); // Get the bitmap BitmapSource = Imaging.CreateBitmapSourceFromMemorySection(_section, _capGrabber.Width, _capGrabber.Height, PixelFormats.Bgr32, _capGrabber.Width * PixelFormats.Bgr32.BitsPerPixel / 8, 0) as InteropBitmap; _capGrabber.Map = _map; // Invoke event if (NewBitmapReady != null) { NewBitmapReady(this, null); } } } catch (Exception ex) { // Trace Trace.TraceError(ex.Message); } }, null); }
protected override void OnPaint(bool isPopup, Structs.Rect dirtyRect, IntPtr buffer, int width, int height) { if (isTakingScreenshot) { //We ignore the first n number of frames if (ignoreFrames > 0) { ignoreFrames--; return; } //Wait until we have a frame that matches the updated size we requested if (screenshotSize.HasValue && screenshotSize.Value.Width == width && screenshotSize.Value.Height == height) { var stride = width * BytesPerPixel; var numberOfBytes = stride * height; //Create out own memory mapped view for the screenshot and copy the buffer into it. //If we were going to create a lot of screenshots then it would be better to allocate a large buffer //and reuse it. var mappedFile = MemoryMappedFile.CreateNew(null, numberOfBytes, MemoryMappedFileAccess.ReadWrite); var viewAccessor = mappedFile.CreateViewAccessor(); CopyMemory(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, (uint)numberOfBytes); //Bitmaps need to be created on the UI thread Dispatcher.BeginInvoke((Action)(() => { var backBuffer = mappedFile.SafeMemoryMappedFileHandle.DangerousGetHandle(); //NOTE: Interopbitmap is not capable of supporting DPI scaling var bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(backBuffer, width, height, PixelFormats.Bgra32, stride, 0); //Using TaskExtensions.TrySetResultAsync extension method so continuation runs on Threadpool screenshotTaskCompletionSource.TrySetResultAsync(bitmap); isTakingScreenshot = false; var browserHost = GetBrowser().GetHost(); //Return the framerate to the previous value browserHost.WindowlessFrameRate = oldFrameRate; //Let the browser know the size changes so normal rendering can continue browserHost.WasResized(); if (viewAccessor != null) { viewAccessor.Dispose(); } if (mappedFile != null) { mappedFile.Dispose(); } })); } } else { base.OnPaint(isPopup, dirtyRect, buffer, width, height); } }
/// <summary> /// Allocate the memory required by the bitmap. /// </summary> /// <param name="pixelWidth">Width of the bitmap in pixels.</param> /// <param name="pixelHeight">Height of the bitmap in pixels.</param> private void CreateInteropBitmap(int pixelWidth, int pixelHeight) { int byteSize = pixelWidth * pixelHeight * 4; this.section = CreateFileMapping(INVALID_HANDLE_VALUE, IntPtr.Zero, PAGE_READWRITE, 0, (uint)byteSize + 4096u, null); this.PixelBuffer = MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, (uint)byteSize); this.InteropBitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(section, pixelWidth, pixelHeight, PixelFormats.Bgr32, pixelWidth * 4, 0); }
public override BitmapSource CreateBitmap() { var stride = Width * BytesPerPixel; Bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(FileMappingHandle, Width, Height, PixelFormat, stride, 0); return(Bitmap); }
public NUIImage(int width, int height) { uint imageSize = (uint)width * (uint)height * 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, width, height, PixelFormats.Bgr32, width * 4, 0) as InteropBitmap; }
private void CreateBitmap(int width, int height) { Debug.Assert(_hSection == IntPtr.Zero); Debug.Assert(_hBitmap == IntPtr.Zero); Debug.Assert(_interopBitmap == null); if (width == 0 || height == 0) { return; } _stride = (width * _format.BitsPerPixel + 7) / 8; int size = height * _stride; _hSection = NativeMethods.CreateFileMapping( PAGE.READWRITE, SEC.NONE, 0, (uint)size, null); BITMAPINFO bmi = new BITMAPINFO(); bmi.biSize = Marshal.SizeOf(bmi); bmi.biWidth = width; bmi.biHeight = -height; // top-down bmi.biPlanes = 1; bmi.biBitCount = 32; bmi.biCompression = BI.RGB; IntPtr hdcScreen = NativeMethods.GetDC(HWND.NULL); _hBitmap = NativeMethods.CreateDIBSection( hdcScreen, ref bmi, DIB.RGB_COLORS, out _pBits, _hSection, 0); // TODO: probably don't need a new DC every time... _hDC = NativeMethods.CreateCompatibleDC(hdcScreen); NativeMethods.SelectObject(_hDC, _hBitmap); _interopBitmap = Imaging.CreateBitmapSourceFromMemorySection( _hSection, width, height, _format, _stride, 0) as InteropBitmap; _bitmapWidth = width; _bitmapHeight = height; }
/// <summary> /// Saves the video properties of the SampleGrabber into member fields /// and creates a file mapping for the captured frames. /// </summary> /// <param name="sampGrabber"> /// The <see cref="ISampleGrabber"/> from which to retreive the sample information. /// </param> protected void SaveSizeInfo(ISampleGrabber sampGrabber) { int hr; // Get the media type from the SampleGrabber var media = new AMMediaType(); hr = sampGrabber.GetConnectedMediaType(media); if (hr != 0) { ErrorLogger.WriteLine("Could not SaveSizeInfo in Camera.Capture. Message: " + DsError.GetErrorText(hr)); } if ((media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero)) { ErrorLogger.WriteLine("Error in Camera.Capture. Unknown Grabber Media Format"); } // Grab the size info var videoInfoHeader = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader)); this.NaturalVideoWidth = videoInfoHeader.BmiHeader.Width; this.NaturalVideoHeight = videoInfoHeader.BmiHeader.Height; this.CreateMemoryMapping(4); Video.Instance.OriginalImageSource = Imaging.CreateBitmapSourceFromMemorySection( this.originalSection, (int)this.NaturalVideoWidth, (int)this.NaturalVideoHeight, PixelFormats.Bgr32, this.Stride, 0) as InteropBitmap; Video.Instance.ColorProcessedImageSource = Imaging.CreateBitmapSourceFromMemorySection( this.colorProcessingSection, (int)this.NaturalVideoWidth, (int)this.NaturalVideoHeight, PixelFormats.Bgr32, this.Stride, 0) as InteropBitmap; Video.Instance.MotionProcessedImageSource = Imaging.CreateBitmapSourceFromMemorySection( this.motionProcessingSection, (int)this.NaturalVideoWidth, (int)this.NaturalVideoHeight, PixelFormats.Bgr32, this.Stride, 0) as InteropBitmap; DsUtils.FreeAMMediaType(media); media = null; }
public BitmapSource GetFrame() { if (CLEyeCameraGetFrame(_camera, _map, 500)) { BitmapSource bmpSrc = Imaging.CreateBitmapSourceFromMemorySection(_section, FrameWidth, FrameHeight, PixelFormats.Bgr32, FrameStride, 0) as InteropBitmap; bmpSrc.Freeze(); return(bmpSrc); } return(null); }
protected void SetSnapshotBitmap(BitmapInfo bitmapInfo) { var stride = bitmapInfo.Width * ((IRenderWebBrowser)this).BytesPerPixel; lock (bitmapInfo.BitmapLock) { var snapshotBitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(bitmapInfo.FileMappingHandle, bitmapInfo.Width, bitmapInfo.Height, PixelFormat, stride, 0); SaveBitmapAsPng(snapshotBitmap, _snapshotFile); _snapshotIsComplete.Set(); } }
public InteropBitmap MapToInteropBitmap(int width, int height) { if ((width != 0) && (height != 0)) { uint byteSize = (uint)(width * height * PixelFormats.Bgr32.BitsPerPixel / 8); _interopBitmapSection = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, byteSize, null); _interopBitmapMap = MapViewOfFile(_interopBitmapSection, 0xF001F, 0, 0, byteSize); var interopBitmap = (Imaging.CreateBitmapSourceFromMemorySection(_interopBitmapSection, width, height, PixelFormats.Bgr32, width * PixelFormats.Bgr32.BitsPerPixel / 8, 0) as InteropBitmap); _map = _interopBitmapMap; return(interopBitmap); } return(null); }
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); }
/// <summary> /// Create a bitmap /// </summary> private void AllocateBitmap() { try { Bitmap = Imaging.CreateBitmapSourceFromMemorySection (_section, _width, _height, PixelFormats.Bgr32, _width * PixelFormats.Bgr32.BitsPerPixel / 8, 0) as InteropBitmap; ViewModel.Get().CaptureImageCommand.OnCanExecuteChanged(); } catch (Exception ex) { } }
public VideoContext(int width, int height) { PixelFormat = PixelFormats.Bgr32; IsAspectRatioChecked = false; Size = width * height * PixelFormat.BitsPerPixel / 8; DisplayWidth = Width = width; DisplayHeight = Height = height; Stride = width * PixelFormat.BitsPerPixel / 8; FileMapping = Win32Api.CreateFileMapping(new IntPtr(-1), IntPtr.Zero, PageAccess.ReadWrite, 0, Size, null); MapView = Win32Api.MapViewOfFile(FileMapping, FileMapAccess.AllAccess, 0, 0, (uint)Size); Image = (InteropBitmap) Imaging.CreateBitmapSourceFromMemorySection(FileMapping, Width, Height, PixelFormat, Stride, 0); }
public override BitmapSource CreateBitmap() { // Unable to create bitmap without valid File Handle (Most likely control is being disposed) if (FileMappingHandle == IntPtr.Zero) { return(null); } var stride = Width * BytesPerPixel; Bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(FileMappingHandle, Width, Height, PixelFormat, stride, 0); return(Bitmap); }
public InteropBitmapHelper(int width, int height, byte[] imageBits, PixelFormat pixelFormat) { _Width = width; _Height = height; _PixelFormat = pixelFormat; int stride = width * pixelFormat.BitsPerPixel / 8; _ColorByteCount = (uint)(height * stride); var colorFileMapping = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, _ColorByteCount, null); _ImageBits = MapViewOfFile(colorFileMapping, 0xF001F, 0, 0, _ColorByteCount); Marshal.Copy(imageBits, 0, _ImageBits, (int)_ColorByteCount); InteropBitmap = Imaging.CreateBitmapSourceFromMemorySection(colorFileMapping, width, height, pixelFormat, stride, 0) as InteropBitmap; }
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); }
/// <summary> /// Initializes an empty Bitmap /// </summary> /// <param name="width">Image width</param> /// <param name="height">Image height</param> /// <param name="pixelFormat">Image format</param> public EditBitmap(int width, int height, PixelFormat pixelFormat) { PixelFormat = pixelFormat; BytesPerPixel = pixelFormat.BitsPerPixel / 8; uint imageSize = (uint)width * (uint)height * (uint)BytesPerPixel; ByteLength = imageSize; // create memory section and map _section = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, imageSize, null); ImageData = MapViewOfFile(_section, 0xF001F, 0, 0, imageSize); BitmapSource = Imaging.CreateBitmapSourceFromMemorySection(_section, width, height, pixelFormat, width * BytesPerPixel, 0) as InteropBitmap; ImageIntPtr = (int *)ImageData; ImageUIntPtr = (uint *)ImageData; ImageBytePtr = (byte *)ImageData; Height = height; Width = width; }
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); }
/// <summary> /// Saves the video properties of the SampleGrabber into member fields /// and creates a file mapping for the captured frames. /// </summary> /// <param name="sampGrabber">The <see cref="ISampleGrabber"/> /// from which to retreive the sample information.</param> private void SaveSizeInfo(ISampleGrabber sampGrabber) { int hr; // Get the media type from the SampleGrabber AMMediaType media = new AMMediaType(); hr = sampGrabber.GetConnectedMediaType(media); if (hr != 0) { ErrorLogger.WriteLine("Could not SaveSizeInfo in Camera.Capture. Message: " + DsError.GetErrorText(hr)); } if ((media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero)) { ErrorLogger.WriteLine("Error in Camera.Capture. Unknown Grabber Media Format"); } // Grab the size info VideoInfoHeader videoInfoHeader = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader)); this.videoWidth = videoInfoHeader.BmiHeader.Width; this.videoHeight = videoInfoHeader.BmiHeader.Height; this.stride = this.videoWidth * (videoInfoHeader.BmiHeader.BitCount / 8); this.bufferLength = this.videoWidth * this.videoHeight * 4; // RGB24 = 3 bytes // create memory section and map for the OpenCV Image. this.section = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, (uint)this.bufferLength, null); this.map = MapViewOfFile(this.section, 0xF001F, 0, 0, (uint)this.bufferLength); this.videoImage = new System.Drawing.Bitmap( this.videoWidth, this.videoHeight, this.stride, System.Drawing.Imaging.PixelFormat.Format32bppRgb, this.map); this.BitmapSource = Imaging.CreateBitmapSourceFromMemorySection( this.section, this.videoWidth, this.videoHeight, PixelFormats.Bgr32, this.videoWidth * 4, 0) as InteropBitmap; DsUtils.FreeAMMediaType(media); media = null; }