Пример #1
0
        internal InteropBitmap(IntPtr hbitmap, IntPtr hpalette, Int32Rect sourceRect, BitmapSizeOptions sizeOptions, WICBitmapAlphaChannelOption alphaOptions)
            : base(true) // Use virtuals
        {
            _bitmapInit.BeginInit();

            using (FactoryMaker myFactory = new FactoryMaker())
            {
                HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromHBITMAP(
                        myFactory.ImagingFactoryPtr,
                        hbitmap,
                        hpalette,
                        alphaOptions,
                        out _unmanagedSource));
                Debug.Assert (_unmanagedSource != null && !_unmanagedSource.IsInvalid);
            }

            _unmanagedSource.CalculateSize();
            _sizeOptions = sizeOptions;
            _sourceRect = sourceRect;
            _syncObject = _unmanagedSource;

            _bitmapInit.EndInit();

            FinalizeCreation();
        }
Пример #2
0
		public static Int32Rect ToInt32Rect(this Rect rect)
		{
			Int32Rect intRect = new Int32Rect(
				(int)rect.X,
				(int)rect.Y,
				(int)rect.Width,
				(int)rect.Height);

			return intRect;
		}
Пример #3
0
        /// <summary>
        /// Construct a CroppedBitmap
        /// </summary>
        /// <param name="source">BitmapSource to apply to the crop to</param>
        /// <param name="sourceRect">Source rect of the bitmap to use</param>
        public CroppedBitmap(BitmapSource source, Int32Rect sourceRect)
            : base(true) // Use base class virtuals
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            _bitmapInit.BeginInit();

            Source = source;
            SourceRect = sourceRect;

            _bitmapInit.EndInit();
            FinalizeCreation();
        }
Пример #4
0
        private unsafe void BackgroundBlockRenderer()
        {
#if DEBUG
            Debug.WriteLine("BackgroundBlockRenderer: Started");
#endif
            if (_graphicBuffer == null)
            {
#if DEBUG
                Debug.WriteLine("BackgroundBlockRenderer: Aborted (graphic = null)");
#endif
                return;
            }
            IsRendering = true;
            try
            {
                while (true)
                {
                    TilesetEntryModel dirtyBlock = null;
                    try
                    {
                        dirtyBlock = _blocks.First(p => p.Dirty);
                    }
                    catch (InvalidOperationException)
                    {
                        break;
                    }
                    RenderProgress = 100 - (int)((100f / (float)_blocks.Count) * (float)_blocks.Count(p => p.Dirty));

                    //targets for tile copies
                    WriteableBitmap newBlockImage        = new WriteableBitmap(16, 16, 96, 96, PixelFormats.Bgra32, null);
                    WriteableBitmap newBlockImageOverlay = new WriteableBitmap(16, 16, 96, 96, PixelFormats.Bgra32, null);
                    newBlockImage.Lock();
                    byte *blockData = (byte *)newBlockImage.BackBuffer;
                    newBlockImageOverlay.Lock();
                    byte *blockDataOverlay = (byte *)newBlockImageOverlay.BackBuffer;

                    //copy tiles
                    for (int k = 0; k < 5; k += 4)
                    {
                        for (int i = 0; i < 4; i++)
                        {
                            //TODO hflip and vflip
                            Int32Rect       pos            = new Int32Rect((i == 1 || i == 3) ? 8 : 0, (i == 2 || i == 3) ? 8 : 0, 8, 8);
                            WriteableBitmap tile           = GetTile(dirtyBlock.Tilemap[i + k].TileID);
                            IList <Color>   currentPalette = _palettes[dirtyBlock.Tilemap[i + k].PalIndex].Value.Colors.Select(p => p.Color).ToList();
                            currentPalette[0] = Color.FromArgb(0, 0, 0, 0); //color 0 = transparent
                            ChangePalette(ref tile, new BitmapPalette(currentPalette));
                            WriteableBitmap fbitmap = new WriteableBitmap(new FormatConvertedBitmap(tile, PixelFormats.Bgra32, null, 0));
                            fbitmap.Lock();
                            byte *fbData = (byte *)fbitmap.BackBuffer;
                            ((k == 0) ? newBlockImage : newBlockImageOverlay).WritePixels(pos, (IntPtr)fbData, 256, 32);
                            fbitmap.Unlock();
                        }
                    }

                    newBlockImageOverlay.AddDirtyRect(new Int32Rect(0, 0, 16, 16));
                    newBlockImageOverlay.Unlock();
                    newBlockImage.AddDirtyRect(new Int32Rect(0, 0, 16, 16));
                    newBlockImage.Unlock();

                    //merge targets
                    AddTransparentBlock(newBlockImage, newBlockImageOverlay);
                    newBlockImage.Freeze();

                    Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() =>
                    {
                        dirtyBlock.Graphic = newBlockImage;
                        dirtyBlock.Dirty   = false;
                    }));
                }
            }
            catch (ThreadAbortException)
            {
#if DEBUG
                Debug.WriteLine("BackgroundBlockRenderer: Aborted");
#endif
            }
#if DEBUG
            Debug.WriteLine("BackgroundBlockRenderer: Ended");
#endif
            IsRendering = false;
        }
Пример #5
0
        /// <summary>
        /// Renders the specified media block.
        /// This needs to return immediately so the calling thread is not disturbed.
        /// </summary>
        /// <param name="mediaBlock">The media block.</param>
        /// <param name="clockPosition">The clock position.</param>
        public void Render(MediaBlock mediaBlock, TimeSpan clockPosition)
        {
            var block = mediaBlock as VideoBlock;

            if (block == null)
            {
                return;
            }
            if (IsRenderingInProgress)
            {
                return;
            }

            IsRenderingInProgress = true;

            Utils.UIEnqueueInvoke(
                DispatcherPriority.Render,
                new Action <VideoBlock, TimeSpan>((b, cP) =>
            {
                try
                {
                    if (TargetBitmap == null || TargetBitmap.PixelWidth != b.PixelWidth || TargetBitmap.PixelHeight != b.PixelHeight)
                    {
                        InitializeTargetBitmap(b);
                    }

                    var updateRect = new Int32Rect(0, 0, b.PixelWidth, b.PixelHeight);
                    TargetBitmap.WritePixels(updateRect, b.Buffer, b.BufferLength, b.BufferStride);
                    MediaElement.RaiseRenderingVideoEvent(TargetBitmap, MediaElement.Container.MediaInfo.Streams[b.StreamIndex], b.StartTime, b.Duration, cP);

                    var scaleTransform = MediaElement.ViewBox.LayoutTransform as ScaleTransform;

                    // Process Aspect Ratio according to block.
                    if (b.AspectWidth != b.AspectHeight)
                    {
                        var scaleX = b.AspectWidth > b.AspectHeight ? (double)b.AspectWidth / b.AspectHeight : 1d;
                        var scaleY = b.AspectHeight > b.AspectWidth ? (double)b.AspectHeight / b.AspectWidth : 1d;

                        if (scaleTransform == null)
                        {
                            scaleTransform = new ScaleTransform(scaleX, scaleY);
                            MediaElement.ViewBox.LayoutTransform = scaleTransform;
                        }

                        if (scaleTransform.ScaleX != scaleX || scaleTransform.ScaleY != scaleY)
                        {
                            scaleTransform.ScaleX = scaleX;
                            scaleTransform.ScaleY = scaleY;
                        }
                    }
                    else
                    {
                        if (scaleTransform != null && (scaleTransform.ScaleX != 1d || scaleTransform.ScaleY != 1d))
                        {
                            scaleTransform.ScaleX = 1d;
                            scaleTransform.ScaleY = 1d;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.Log(MediaElement, MediaLogMessageType.Error, $"{nameof(VideoRenderer)} {ex.GetType()}: {ex.Message}. Stack Trace:\r\n{ex.StackTrace}");
                }
                finally
                {
                    IsRenderingInProgress = false;
                }
            }), block,
                clockPosition);
        }
Пример #6
0
        public override WriteableBitmap Draw(DrawingArgs args)
        {
            int scale         = (int)args.Scale;
            var h             = args.CanvasHeight;
            var w             = h;
            var fractalBitmap = new WriteableBitmap(w * scale, h * scale, 96.0, 96.0, PixelFormats.Bgra32, null);

            h = h * scale;
            w = w * scale;

            var stride    = w * 4;
            var pixelData = new byte[h * stride];

            double xMin = double.NaN;
            double yMin = double.NaN;
            double xMax = double.NaN;
            double yMax = double.NaN;

            double r = CalculateR(C);

            if (Double.IsNaN(xMin) || Double.IsNaN(xMax) || Double.IsNaN(yMin) || Double.IsNaN(yMax))
            {
                xMin = -r;
                yMin = -r;
                xMax = r;
                yMax = r;
            }
            double xStep = Math.Abs(xMax - xMin) / w;
            double yStep = Math.Abs(yMax - yMin) / h;

            var xyIdx  = new Dictionary <int, IDictionary <int, int> >();
            int maxIdx = 0;

            for (int i = 0; i < w; i++)
            {
                xyIdx.Add(i, new Dictionary <int, int>());
                for (int j = 0; j < h; j++)
                {
                    double x     = xMin + i * xStep;
                    double y     = yMin + j * yStep;
                    var    z     = new Complex(x, y);
                    var    zIter = SqPolyIteration(z, C, args.IterationsCount, r);
                    int    idx   = zIter.Count - 1;
                    if (maxIdx < idx)
                    {
                        maxIdx = idx;
                    }
                    xyIdx[i].Add(j, idx);
                }
            }
            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    int    idx = xyIdx[i][j];
                    double x   = xMin + i * xStep;
                    double y   = yMin + j * yStep;
                    var    z   = new Complex(x, y);

                    var color = ComplexHeatMap(idx, 0, maxIdx, z, r);
                    pixelData[j * stride + (w - i - 1) * 4 + 0] = color.R;
                    pixelData[j * stride + (w - i - 1) * 4 + 1] = color.G;
                    pixelData[j * stride + (w - i - 1) * 4 + 2] = color.B;
                    pixelData[j * stride + (w - i - 1) * 4 + 3] = color.A;
                }
            }

            var rect      = new Int32Rect(0, 0, w - 1, h - 1);
            var rawStride = (w * PixelFormats.Bgra32.BitsPerPixel + 7) / 8;

            fractalBitmap.WritePixels(rect, pixelData, rawStride, 0);

            return(fractalBitmap);
        }
Пример #7
0
        /// <summary>
        /// Draw qrCode dark modules at given position. (It will also include quiet zone area. Set it to zero to exclude quiet zone)
        /// </summary>
        /// <exception cref="ArgumentNullException">Bitmatrix, wBitmap should not equal to null</exception>
        /// <exception cref="ArgumentOutOfRangeException">wBitmap's pixel width or height should not equal to zero</exception>
        public void DrawDarkModule(WriteableBitmap wBitmap, BitMatrix matrix, int offsetX, int offsetY)
        {
            if (matrix == null)
            {
                throw new ArgumentNullException("Bitmatrix");
            }

            DrawingSize size = ISize.GetSize(matrix.Width);

            if (wBitmap == null)
            {
                throw new ArgumentNullException("wBitmap");
            }
            else if (wBitmap.PixelHeight == 0 || wBitmap.PixelWidth == 0)
            {
                throw new ArgumentOutOfRangeException("wBitmap", "WriteableBitmap's pixelHeight or PixelWidth are equal to zero");
            }

            int padding = (size.CodeWidth - size.ModuleSize * matrix.Width) / 2;

            int preX       = -1;
            int moduleSize = size.ModuleSize;

            if (moduleSize == 0)
            {
                return;
            }

            for (int y = 0; y < matrix.Width; y++)
            {
                for (int x = 0; x < matrix.Width; x++)
                {
                    if (matrix[x, y])
                    {
                        if (preX == -1)
                        {
                            preX = x;
                        }
                        if (x == matrix.Width - 1)
                        {
                            Int32Rect moduleArea =
                                new Int32Rect(preX * moduleSize + padding + offsetX,
                                              y * moduleSize + padding + offsetY,
                                              (x - preX + 1) * moduleSize,
                                              moduleSize);
                            wBitmap.FillRectangle(moduleArea, DarkColor);
                            preX = -1;
                        }
                    }
                    else if (preX != -1)
                    {
                        Int32Rect moduleArea =
                            new Int32Rect(preX * moduleSize + padding + offsetX,
                                          y * moduleSize + padding + offsetY,
                                          (x - preX) * moduleSize,
                                          moduleSize);
                        wBitmap.FillRectangle(moduleArea, DarkColor);
                        preX = -1;
                    }
                }
            }
        }
Пример #8
0
        [FriendAccessAllowed] // Built into Core, also used by Framework.
        unsafe internal void CriticalCopyPixels(Int32Rect sourceRect, Array pixels, int stride, int offset)
        {
            ReadPreamble();
            _bitmapInit.EnsureInitializedComplete();
            CompleteDelayedCreation();

            if (pixels == null)
                throw new System.ArgumentNullException("pixels");

            if (pixels.Rank != 1)
                throw new ArgumentException(SR.Get(SRID.Collection_BadRank), "pixels");

            if (offset < 0)
            {
                HRESULT.Check((int)WinCodecErrors.WINCODEC_ERR_VALUEOVERFLOW);
            }

            int elementSize = -1;

            if (pixels is byte[])
                elementSize = 1;
            else if (pixels is short[] || pixels is ushort[])
                elementSize = 2;
            else if (pixels is int[] || pixels is uint[] || pixels is float[])
                elementSize = 4;
            else if (pixels is double[])
                elementSize = 8;

            if (elementSize == -1)
                throw new ArgumentException(SR.Get(SRID.Image_InvalidArrayForPixel));

            int destBufferSize = checked(elementSize * (pixels.Length - offset));


            if (pixels is byte[])
            {
                fixed (void* pixelArray = &((byte[])pixels)[offset])
                    CriticalCopyPixels(sourceRect, (IntPtr)pixelArray, destBufferSize, stride);
            }
            else if (pixels is short[])
            {
                fixed (void* pixelArray = &((short[])pixels)[offset])
                    CriticalCopyPixels(sourceRect, (IntPtr)pixelArray, destBufferSize, stride);
            }
            else if (pixels is ushort[])
            {
                fixed (void* pixelArray = &((ushort[])pixels)[offset])
                    CriticalCopyPixels(sourceRect, (IntPtr)pixelArray, destBufferSize, stride);
            }
            else if (pixels is int[])
            {
                fixed (void* pixelArray = &((int[])pixels)[offset])
                    CriticalCopyPixels(sourceRect, (IntPtr)pixelArray, destBufferSize, stride);
            }
            else if (pixels is uint[])
            {
                fixed (void* pixelArray = &((uint[])pixels)[offset])
                    CriticalCopyPixels(sourceRect, (IntPtr)pixelArray, destBufferSize, stride);
            }
            else if (pixels is float[])
            {
                fixed (void* pixelArray = &((float[])pixels)[offset])
                    CriticalCopyPixels(sourceRect, (IntPtr)pixelArray, destBufferSize, stride);
            }
            else if (pixels is double[])
            {
                fixed (void* pixelArray = &((double[])pixels)[offset])
                    CriticalCopyPixels(sourceRect, (IntPtr)pixelArray, destBufferSize, stride);
            }

        }
        private void CreateOrUpdateBitmap(bool isPopup, Rect dirtyRect, IntPtr buffer, int width, int height, Image image, ref Size currentSize, ref MemoryMappedFile mappedFile, ref MemoryMappedViewAccessor viewAccessor)
        {
            if (image.Dispatcher.HasShutdownStarted)
            {
                return;
            }

            var createNewBitmap = false;

            lock (lockObject)
            {
                int pixels        = width * height;
                int numberOfBytes = pixels * BytesPerPixel;

                createNewBitmap = mappedFile == null || currentSize.Height != height || currentSize.Width != width;

                if (createNewBitmap)
                {
                    ReleaseMemoryMappedView(ref mappedFile, ref viewAccessor);

                    mappedFile = MemoryMappedFile.CreateNew(null, numberOfBytes, MemoryMappedFileAccess.ReadWrite);

                    viewAccessor = mappedFile.CreateViewAccessor();

                    currentSize.Height = height;
                    currentSize.Width  = width;
                }

                //TODO: Performance analysis to determine which is the fastest memory copy function
                //NativeMethodWrapper.CopyMemoryUsingHandle(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, numberOfBytes);
                CopyMemory(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, (uint)numberOfBytes);

                //Take a reference to the backBufferHandle, once we're on the UI thread we need to check if it's still valid
                var backBufferHandle = mappedFile.SafeMemoryMappedFileHandle;

                //Invoke on the WPF UI Thread
                image.Dispatcher.BeginInvoke((Action)(() =>
                {
                    lock (lockObject)
                    {
                        if (backBufferHandle.IsClosed || backBufferHandle.IsInvalid)
                        {
                            return;
                        }

                        if (createNewBitmap)
                        {
                            if (image.Source != null)
                            {
                                image.Source = null;
                                //TODO: Is this still required in newer versions of .Net?
                                GC.Collect(1);
                            }

                            var stride = width * BytesPerPixel;
                            var bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(backBufferHandle.DangerousGetHandle(), width, height, PixelFormat, stride, 0);
                            image.Source = bitmap;
                        }
                        else
                        {
                            if (image.Source != null)
                            {
                                var sourceRect = new Int32Rect(dirtyRect.X, dirtyRect.Y, dirtyRect.Width, dirtyRect.Height);
                                var bitmap = (InteropBitmap)image.Source;
                                bitmap.Invalidate(sourceRect);
                            }
                        }
                    }
                }), dispatcherPriority);
            }
        }
Пример #10
0
 // AddZone
 //  Adds the specified Zone to the end of the Zones list, and fires a property changed notification for the Zones property
 public void AddZone(Int32Rect zone)
 {
     Zones.Add(zone);
     TemplateZoneCount = Zones.Count;
     UpdateLayout();
 }
Пример #11
0
        private void SaveFrame(SafeMILHandle frameEncodeHandle, SafeMILHandle encoderOptions, BitmapFrame frame)
        {
            SetupFrame(frameEncodeHandle, encoderOptions);

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeInitialized;

            // Set the size
            HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetSize(
                frameEncodeHandle,
                frame.PixelWidth,
                frame.PixelHeight
                ));

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeSizeSet;

            // Set the resolution
            double dpiX = frame.DpiX;
            double dpiY = frame.DpiY;

            if (dpiX <= 0)
            {
                dpiX = 96;
            }
            if (dpiY <= 0)
            {
                dpiY = 96;
            }

            HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetResolution(
                frameEncodeHandle,
                dpiX,
                dpiY
                ));

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeResolutionSet;

            if (_supportsFrameThumbnails)
            {
                // Set the thumbnail.
                BitmapSource thumbnail = frame.Thumbnail;

                if (thumbnail != null)
                {
                    SafeMILHandle thumbnailHandle = thumbnail.WicSourceHandle;

                    lock (thumbnail.SyncObject)
                    {
                        HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetThumbnail(
                            frameEncodeHandle,
                            thumbnailHandle
                            ));

                        // Helpful for debugging stress and remote dumps
                        _encodeState = EncodeState.FrameEncodeThumbnailSet;
                    }
                }
            }

            // if the source has been color corrected, we want to use a corresponding color profile
            if (frame._isColorCorrected)
            {
                ColorContext colorContext = new ColorContext(frame.Format);
                IntPtr[] colorContextPtrs = new IntPtr[1] { colorContext.ColorContextHandle.DangerousGetHandle() };

                int hr = UnsafeNativeMethods.WICBitmapFrameEncode.SetColorContexts(
                    frameEncodeHandle,
                    1,
                    colorContextPtrs
                    );

                // It's possible that some encoders may not support color contexts so don't check hr
                if (hr == HRESULT.S_OK)
                {
                    // Helpful for debugging stress and remote dumps
                    _encodeState = EncodeState.FrameEncodeColorContextsSet;
                }
            }
            // if the caller has explicitly provided color contexts, add them to the encoder
            else
            {
                IList<ColorContext> colorContexts = frame.ColorContexts;
                if (colorContexts != null && colorContexts.Count > 0)
                {             
                    int count = colorContexts.Count;

                    // Marshal can't convert SafeMILHandle[] so we must
                    {
                        IntPtr[] colorContextPtrs = new IntPtr[count];
                        for (int i = 0; i < count; ++i)
                        {
                            colorContextPtrs[i] = colorContexts[i].ColorContextHandle.DangerousGetHandle();
                        }

                        int hr = UnsafeNativeMethods.WICBitmapFrameEncode.SetColorContexts(
                            frameEncodeHandle,
                            (uint)count,
                            colorContextPtrs
                            );

                        // It's possible that some encoders may not support color contexts so don't check hr
                        if (hr == HRESULT.S_OK)
                        {
                            // Helpful for debugging stress and remote dumps
                            _encodeState = EncodeState.FrameEncodeColorContextsSet;
                        }
                    }
                }
            }

            // Set the pixel format and palette

            lock (frame.SyncObject)
            {
                SafeMILHandle outSourceHandle = new SafeMILHandle();
                SafeMILHandle bitmapSourceHandle = frame.WicSourceHandle;
                SafeMILHandle paletteHandle = new SafeMILHandle();

                // Set the pixel format and palette of the bitmap.
                // This could (but hopefully won't) introduce a format converter.
                HRESULT.Check(UnsafeNativeMethods.WICCodec.WICSetEncoderFormat(
                    bitmapSourceHandle,
                    paletteHandle,
                    frameEncodeHandle,
                    out outSourceHandle
                    ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeFormatSet;
                _writeSourceHandles.Add(outSourceHandle);

                // Set the metadata
                if (_supportsFrameMetadata)
                {
                    BitmapMetadata metadata = frame.Metadata as BitmapMetadata;

                    // If the frame has metadata associated with a different container format, then we ignore it.
                    if (metadata != null && metadata.GuidFormat == ContainerFormat)
                    {
                        SafeMILHandle /* IWICMetadataQueryWriter */ metadataHandle = new SafeMILHandle();

                        HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.GetMetadataQueryWriter(
                            frameEncodeHandle,
                            out metadataHandle
                            ));

                        PROPVARIANT propVar = new PROPVARIANT();

                        try
                        {
                            propVar.Init(metadata);

                            lock (metadata.SyncObject)
                            {
                                HRESULT.Check(UnsafeNativeMethods.WICMetadataQueryWriter.SetMetadataByName(
                                    metadataHandle,
                                    "/",
                                    ref propVar
                                    ));

                                // Helpful for debugging stress and remote dumps
                                _encodeState = EncodeState.FrameEncodeMetadataSet;
                            }
                        }
                        finally
                        {
                            propVar.Clear();
                        }
                    }
                }

                Int32Rect r = new Int32Rect();
                HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.WriteSource(
                    frameEncodeHandle,
                    outSourceHandle,
                    ref r
                    ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeSourceWritten;

                HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.Commit(
                    frameEncodeHandle
                    ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeCommitted;
            }
        }
Пример #12
0
        private unsafe void InitializeNewResultImage(ManagedImage mImg)
        {
            //byte* managedImageDataPtr = mImg.data; IntPtr dataPtr = new IntPtr(managedImageDataPtr);
            m_pixelsFormat = mImg.pixelFormat;
            ManagedImage manImg = new ManagedImage();

            if (m_pixelsFormat == PixelFormat.PixelFormatMono12 || m_pixelsFormat == PixelFormat.PixelFormatMono16 || m_pixelsFormat == PixelFormat.PixelFormatMono8 || m_pixelsFormat == PixelFormat.PixelFormatSignedMono16)
            {
                mImg.Convert(PixelFormat.PixelFormatMono8, manImg);
            }
            else
            {
                mImg.Convert(PixelFormat.PixelFormatBgr, manImg);
            }


            int   height = (int)manImg.rows, width = (int)manImg.cols, stride = (int)manImg.stride, dataSize = height * stride, bpp = (int)manImg.bitsPerPixel / 8;
            byte *imageData = manImg.data;
            //byte[] imgData = new byte[dataSize];

            //Marshal.Copy(dataPtr, imgData, 0, dataSize);
            Point     cursorPosition = this.CurrentCursorPosition;
            int       xRec = (int)(cursorPosition.X / this.VideoStreamAreaActualWidth * width), yRec = (int)(cursorPosition.Y / this.VideoStreamAreaActualHeight * height);
            Int32Rect rec = GetValidRectangle(xRec, yRec, width, height);

            m_currentRec = rec;

            byte[] currBytes = new byte[rec.Height * rec.Width * bpp];

            ManagedImage managImgForWrbmp = new ManagedImage();

            manImg.ConvertToWriteAbleBitmap(managImgForWrbmp);
            WriteableBitmap bmpTemp = managImgForWrbmp.writeableBitmap;

            bmpTemp.CopyPixels(rec, currBytes, rec.Width * bpp, 0);
            m_currentBytes = currBytes;
            OnSetNeededCameraProperty();
            OnCurrentBytesUpdated();

            int xBegin = rec.X, xEnd = rec.X + rec.Width, yBegin = rec.Y, yEnd = rec.Y + rec.Height;

            for (int xPix = xBegin; xPix <= xEnd; xPix++)
            {
                for (int yPix = yBegin; yPix <= yEnd; yPix++)
                {
                    if (yPix == yBegin || yPix == yEnd || xPix == xBegin || xPix == xEnd)
                    {
                        int pixelPosition = yPix * stride + xPix * bpp;

                        if (manImg.pixelFormat == PixelFormat.PixelFormatBgr)
                        {
                            imageData[pixelPosition]     = 0;
                            imageData[pixelPosition + 1] = 0;
                            imageData[pixelPosition + 2] = 0;
                        }
                        else
                        {
                            imageData[pixelPosition] = 0;
                        }
                    }
                }
            }

            ManagedImage temp = new ManagedImage();

            manImg.ConvertToBitmapSource(temp);
            temp.bitmapsource.Freeze();
            this.NewResultImage = temp.bitmapsource;
            OnNewResultImageIsReady();
        }
Пример #13
0
        public ErrorCode ReadFrom(Uri requestUri, IEnumerable <KeyValuePair <string, string> > queryNameValuePairs)
        {
            foreach (var item in queryNameValuePairs)
            {
                switch (item.Key)
                {
                case "s":
                {
                    var s = item.Value;
                    if (s.StartsWith("//"))
                    {
                        s = requestUri.Scheme + ":" + s;
                    }
                    if (!Uri.TryCreate(s, UriKind.Absolute, out Source))
                    {
                        return(ErrorCode.SourceUriFormatError);
                    }
                }
                break;

                case "q":
                    int quality;
                    if (!TryConvert(item.Value, out quality))
                    {
                        return(ErrorCode.QualityParseError);
                    }
                    if (!(0 <= quality && quality <= 100))
                    {
                        return(ErrorCode.QualityOutOfRange);
                    }
                    Quality = quality;
                    break;

                case "w":
                    int pixelWidth;
                    if (!TryConvert(item.Value, out pixelWidth))
                    {
                        return(ErrorCode.PixelWidthParseError);
                    }
                    if (pixelWidth < 0)
                    {
                        return(ErrorCode.PixelWidthOutOfRange);
                    }
                    PixelWidth = pixelWidth;
                    break;

                case "h":
                    int pixelHeight;
                    if (!TryConvert(item.Value, out pixelHeight))
                    {
                        return(ErrorCode.PixelHeightParseError);
                    }
                    if (pixelHeight < 0)
                    {
                        return(ErrorCode.PixelHeightOutOfRange);
                    }
                    PixelHeight = pixelHeight;
                    break;

                case "t":
                    ImageType type;
                    if (!Enum.TryParse(item.Value, true, out type))
                    {
                        return(ErrorCode.ImageTypeParseError);
                    }
                    if (type == 0)
                    {
                        return(ErrorCode.ImageTypeOutOfRange);
                    }
                    Type = type;
                    break;

                case "c":
                    if (item.Value == "smart")
                    {
                        CropSmart = true;
                        break;
                    }
                    // the crop rectange is in percentages,
                    // based on the source image dimension
                    // we use this to get the actual crop
                    Int32Rect crop;
                    try
                    {
                        crop = Int32Rect.Parse(item.Value);
                    }
                    catch (Exception)
                    {
                        return(ErrorCode.CropRectParseError);
                    }
                    if (!((0 <= (crop.X + crop.Width)) & (crop.X + crop.Width) <= 100))
                    {
                        return(ErrorCode.CropRectOutOfRange);
                    }
                    if (!((0 <= (crop.Y + crop.Height)) & (crop.Y + crop.Height) <= 100))
                    {
                        return(ErrorCode.CropRectOutOfRange);
                    }
                    Crop = crop;
                    break;

                case "f":
                    FittingType fit;
                    if (!Enum.TryParse(item.Value, true, out fit))
                    {
                        return(ErrorCode.FittingTypeParseError);
                    }
                    Fit = fit;
                    break;

                case "bg-color":
                    try
                    {
                        if (HexPattern.IsMatch(item.Value))
                        {
                            var s = item.Value;
                            if (s.Length == 3)
                            {
                                // shorthand #fc0 -> #ffcc00
                                s = s.Substring(0, 1) + s.Substring(0, 1)
                                    + s.Substring(1, 1) + s.Substring(1, 1)
                                    + s.Substring(2, 1) + s.Substring(2, 1)
                                ;
                            }
                            BackgroundColor = (Color)ColorConverter.ConvertFromString("#" + item.Value);
                        }
                        else
                        {
                            BackgroundColor = (Color)ColorConverter.ConvertFromString(item.Value);
                        }
                    }
                    catch (Exception)
                    {
                        return(ErrorCode.BackgroundColorParseError);
                    }
                    break;

                case "debug":
                {
                    IsDebug = item.Value == "1";
                    break;
                }
                }
            }

            if (Source == null)
            {
                return(ErrorCode.SourceIsRequired);
            }

            return(ErrorCode.None);
        }
Пример #14
0
 public virtual void CopyPixels(Int32Rect sourceRect, Array pixels, int stride, int offset)
 {
     throw new NotImplementedException();
 }
Пример #15
0
 public virtual void CopyPixels(Int32Rect sourceRect, IntPtr butter, int bufferSize, int stride)
 {
     throw new NotImplementedException();
 }
Пример #16
0
        private void WriteObjectImage(VPort cameraPort, Bitmap image, Rectangle rectSrc, bool center)
        {
            Rectangle rectTarget     = rectSrc;
            int       srcPixelShiftX = 0;
            int       srcPixelShiftY = 0;

            if (rectSrc.Width == 0 && rectSrc.Height == 0)
            {
                logger.Log("Write Object Image Called with Rect with zero height and width!");
                return;
            }

            if (center)
            {
                rectTarget.X   = (int)((image.Width - rectSrc.Width) / 2.0);
                rectTarget.Y   = (int)((image.Height - rectSrc.Height) / 2.0);
                srcPixelShiftX = rectTarget.X - rectSrc.X;
                srcPixelShiftY = rectTarget.Y - rectSrc.Y;
            }

            // create the destination based upon layer one
            BitmapData bmpData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            int        stride  = bmpData.Stride;

            image.UnlockBits(bmpData);

            WriteableBitmap composite  = new WriteableBitmap(image.Width, image.Height, 96, 96, System.Windows.Media.PixelFormats.Rgb24, null);
            Int32Rect       sourceRect = new Int32Rect(0, 0, (int)image.Width, (int)image.Height);

            byte[] pixels = new byte[stride * image.Height];

            for (int x = 0; x < image.Width; ++x)
            {
                for (int y = 0; y < image.Height; ++y)
                {
                    if (rectSrc.Contains(x, y))
                    {
                        Color clr = image.GetPixel(x, y);
                        pixels[stride * (y + srcPixelShiftY) + 3 * (x + srcPixelShiftX)]     = clr.R;
                        pixels[stride * (y + srcPixelShiftY) + 3 * (x + srcPixelShiftX) + 1] = clr.G;
                        pixels[stride * (y + srcPixelShiftY) + 3 * (x + srcPixelShiftX) + 2] = clr.B;
                    }
                    else if (!rectTarget.Contains(x, y))
                    {
                        pixels[stride * y + 3 * x]     = 0x00;
                        pixels[stride * y + 3 * x + 1] = 0x00;
                        pixels[stride * y + 3 * x + 2] = 0x00;
                    }
                }
            }
            composite.WritePixels(sourceRect, pixels, stride, 0);

            // encode the bitmap to the output file
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(composite));
            string filepath = GetMediaFileName(cameraPort.GetInfo().GetFriendlyName(), MediaType.MediaType_Image_JPEG);

            if (null == filepath)
            {
                logger.Log("GetMediaFileName failed to get a file name, are there more than 10 files of the same name?");
                return;
            }

            using (var stream = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
            {
                encoder.Save(stream);
            }
        }
Пример #17
0
        public void Invalidate(Int32Rect? dirtyRect)
        {
            SecurityHelper.DemandUnmanagedCode();

            // A null dirty rect indicates the entire bitmap should be
            // invalidated, while a value indicates that only a dirty rect
            // should be invalidated.
            if (dirtyRect.HasValue)
            {
                dirtyRect.Value.ValidateForDirtyRect("dirtyRect", _pixelWidth, _pixelHeight);
            
                if (!dirtyRect.Value.HasArea)
                {
                    // Nothing needs done.
                    return;
                }
            }

            WritePreamble();

            if (_unmanagedSource != null)
            {
                if(UsableWithoutCache)
                {
                    // For bitmap sources that do not require caching on the
                    // UI thread, we can just add a dirty rect to the
                    // CWICWrapperBitmap.  The render thread will respond by
                    // updating the affected realizations by copying from this
                    // bitmap.  Since this bitmap is not cached, it will get
                    // the most current bits.
                    unsafe
                    {
                        for (int i = 0, numChannels = _duceResource.GetChannelCount(); i < numChannels; ++i)
                        {
                            DUCE.Channel channel = _duceResource.GetChannel(i);
                    
                            DUCE.MILCMD_BITMAP_INVALIDATE data;
                            data.Type = MILCMD.MilCmdBitmapInvalidate;
                            data.Handle = _duceResource.GetHandle(channel);

                            bool useDirtyRect = dirtyRect.HasValue;
                            if(useDirtyRect)
                            {
                                data.DirtyRect.left = dirtyRect.Value.X;
                                data.DirtyRect.top = dirtyRect.Value.Y;
                                data.DirtyRect.right = dirtyRect.Value.X + dirtyRect.Value.Width;
                                data.DirtyRect.bottom = dirtyRect.Value.Y + dirtyRect.Value.Height;
                            }
                            
                            data.UseDirtyRect = (uint)(useDirtyRect ? 1 : 0);
                    
                            channel.SendCommand((byte*)&data, sizeof(DUCE.MILCMD_BITMAP_INVALIDATE));
                        }
                    }
                }
                else
                {
                    // For bitmap sources that require caching on the
                    // UI thread, we can't just add a dirty rect to the
                    // CWICWrapperBitmap because it will just read the cached
                    // contents again.  We really need a caching bitmap
                    // implementation that understands dirty rects and will
                    // update its cache.  Unfortunately, today the caching
                    // bitmap is a standard WIC implementation, and does not
                    // support this functionality.
                    //
                    // For now, we just recreate the caching bitmap.  Setting
                    // _needsUpdate to true will cause BitmapSource to throw
                    // away the old DUCECompatiblePtr, and create a new caching
                    // bitmap to send to the render thread. Since the render
                    // thread sees a brand new bitmap, it will copy the bits out.
                    _needsUpdate = true;
                    RegisterForAsyncUpdateResource();
                }
            } 

            WritePostscript();
        }
Пример #18
0
        public static byte[] ExtractPixelSection(byte[] sourcePixels, int sourceBitsPerPixel, int sourceStride, Int32Rect sectionRect, System.Drawing.Color[] transparentColors)
        {
            int  length = sectionRect.Width * sectionRect.Height * 4;
            int  num1   = sourceBitsPerPixel / 8;
            bool flag   = false;

            if (sourceBitsPerPixel == 32)
            {
                flag = true;
                int num2 = 0;
                while (num2 < sourcePixels.Length)
                {
                    if (sourcePixels[num2 + 3] != 0)
                    {
                        flag = false;
                        break;
                    }
                    num2 += 4;
                }
            }
            byte[] numArray = new byte[length];
            for (int index1 = 0; index1 < sectionRect.Height; ++index1)
            {
                for (int index2 = 0; index2 < sectionRect.Width; ++index2)
                {
                    var  cDisplayClass50 = new ColorClass();
                    int  index3          = (index2 + sectionRect.X) * num1 + (index1 + sectionRect.Y) * sourceStride;
                    int  index4          = index2 * 4 + index1 * (sectionRect.Width * 4);
                    byte num2            = sourcePixels[index3];
                    byte num3            = sourcePixels[index3 + 1];
                    byte num4            = sourcePixels[index3 + 2];
                    byte num5            = sourceBitsPerPixel == 32 ? sourcePixels[index3 + 3] : byte.MaxValue;
                    cDisplayClass50.C = System.Drawing.Color.FromArgb(num4, num3, num2);
                    if (Array.FindIndex(transparentColors, cDisplayClass50.IsEquals) != -1)
                    {
                        num5 = 0;
                    }
                    else if (flag)
                    {
                        num5 = byte.MaxValue;
                    }
                    if (num5 == 0)
                    {
                        num2 = 0;
                        num3 = 0;
                        num4 = 0;
                    }
                    numArray[index4]     = num2;
                    numArray[index4 + 1] = num3;
                    numArray[index4 + 2] = num4;
                    numArray[index4 + 3] = num5;
                }
            }
            return(numArray);
        }
Пример #19
0
        public void imageMode(object sender, RoutedEventArgs e)
        {
            var screen = new OpenFileDialog();

            screen.Filter           = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
            screen.InitialDirectory = @"C:\";
            screen.Title            = "Please select an image file to encrypt.";
            if (screen.ShowDialog() == true)
            {
                filePath = screen.FileName;
                var source = new BitmapImage(
                    new Uri(screen.FileName, UriKind.Absolute));
                previewImage.Width  = 300;
                previewImage.Height = 240;
                previewImage.Source = source;


                // Bat dau cat thanh 9 manh
                int count = 0;
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        if (!((i == 2) && (j == 2)))
                        {
                            TransformedBitmap mybitmapIMG;
                            if (source.Height > source.Width)
                            {
                                double scaleTransfH = 300 / source.Height;
                                mybitmapIMG = new TransformedBitmap(source, new ScaleTransform(scaleTransfH, scaleTransfH));
                                imgWidth    = (int)(mybitmapIMG.PixelWidth / 3);
                                imgHeight   = (int)(mybitmapIMG.PixelHeight / 3);
                            }
                            else
                            {
                                double scaleTransfW = 300 / source.Width;
                                mybitmapIMG = new TransformedBitmap(source, new ScaleTransform(scaleTransfW, scaleTransfW));
                                imgWidth    = (int)(mybitmapIMG.PixelWidth / 3);
                                imgHeight   = (int)(mybitmapIMG.PixelHeight / 3);
                            }
                            drawLines(startX, startY, imgWidth, imgHeight);
                            var rect       = new Int32Rect(j * imgWidth, i * imgHeight, imgWidth, imgHeight);
                            var cropBitmap = new CroppedBitmap(mybitmapIMG,
                                                               rect);
                            var cropImage = new Image();
                            cropImage.Stretch = Stretch.Fill;
                            cropImage.Width   = imgWidth;
                            cropImage.Height  = imgHeight;
                            cropImage.Source  = cropBitmap;
                            canvas.Children.Add(cropImage);
                            Canvas.SetLeft(cropImage, startX + j * (imgWidth + 2));
                            Canvas.SetTop(cropImage, startY + i * (imgHeight + 2));
                            cropImage.MouseLeftButtonDown      += CropImage_MouseLeftButtonDown;
                            cropImage.PreviewMouseLeftButtonUp += CropImage_MouseLeftButtonUp;
                            cropImage.Tag  = new Tuple <int, int>(i, j);
                            cropImage.Name = $"s{count}";
                            listCropImg.Add(cropImage);
                            count++;
                        }
                    }
                }
                Image nullImage = new Image();
                listCropImg.Add(nullImage);
            }
            else
            {
                this.Window_Loaded(sender, e);
            }
        }
Пример #20
0
 public static byte[] ExtractPixelSection(byte[] sourcePixels, int sourceBitsPerPixel, int sourceStride, Int32Rect sectionRect)
 {
     System.Drawing.Color[] transparentColors =
     {
         System.Drawing.Color.FromArgb(0,             254, 0),
         System.Drawing.Color.FromArgb(byte.MaxValue,   0, byte.MaxValue)
     };
     return(ExtractPixelSection(sourcePixels, sourceBitsPerPixel, sourceStride, sectionRect, transparentColors));
 }
Пример #21
0
        public virtual void CopyPixels(Int32Rect sourceRect, Array pixels, int stride, int offset)
        {

            EnsureShouldUseVirtuals();

            // Demand Site Of origin on the URI if it passes then this  information is ok to expose
            CheckIfSiteOfOrigin();

            CriticalCopyPixels(sourceRect, pixels, stride, offset);
        }
Пример #22
0
        // UpdateLayoutModels
        // Update the five default layouts based on the new ZoneCount
        private void UpdateLayoutModels()
        {
            // Update the "Focus" Default Layout
            _focusModel.Zones.Clear();

            // Sanity check for imported settings that may have invalid data
            if (ZoneCount < 1)
            {
                ZoneCount = 3;
            }

            // If changing focus layout zones size and/or increment,
            // same change should be applied in ZoneSet.cpp (ZoneSet::CalculateFocusLayout)
            Int32Rect focusZoneRect       = new Int32Rect(100, 100, (int)(WorkArea.Width * 0.4), (int)(WorkArea.Height * 0.4));
            int       focusRectXIncrement = (ZoneCount <= 1) ? 0 : 50;
            int       focusRectYIncrement = (ZoneCount <= 1) ? 0 : 50;

            for (int i = 0; i < ZoneCount; i++)
            {
                _focusModel.Zones.Add(focusZoneRect);
                focusZoneRect.X += focusRectXIncrement;
                focusZoneRect.Y += focusRectYIncrement;
            }

            // Update the "Rows" and "Columns" Default Layouts
            // They can share their model, just transposed
            _rowsModel.CellChildMap    = new int[ZoneCount, 1];
            _columnsModel.CellChildMap = new int[1, ZoneCount];
            _rowsModel.Rows            = _columnsModel.Columns = ZoneCount;
            _rowsModel.RowPercents     = _columnsModel.ColumnPercents = new List <int>(ZoneCount);

            for (int i = 0; i < ZoneCount; i++)
            {
                _rowsModel.CellChildMap[i, 0]    = i;
                _columnsModel.CellChildMap[0, i] = i;

                // Note: This is NOT equal to _multiplier / ZoneCount and is done like this to make
                // the sum of all RowPercents exactly (_multiplier).
                // _columnsModel is sharing the same array
                _rowsModel.RowPercents.Add(((_multiplier * (i + 1)) / ZoneCount) - ((_multiplier * i) / ZoneCount));
            }

            // Update the "Grid" Default Layout
            int rows = 1;

            while (ZoneCount / rows >= rows)
            {
                rows++;
            }

            rows--;
            int cols = ZoneCount / rows;

            if (ZoneCount % rows == 0)
            {
                // even grid
            }
            else
            {
                cols++;
            }

            _gridModel.Rows           = rows;
            _gridModel.Columns        = cols;
            _gridModel.RowPercents    = new List <int>(rows);
            _gridModel.ColumnPercents = new List <int>(cols);
            _gridModel.CellChildMap   = new int[rows, cols];

            // Note: The following are NOT equal to _multiplier divided by rows or columns and is
            // done like this to make the sum of all RowPercents exactly (_multiplier).
            for (int row = 0; row < rows; row++)
            {
                _gridModel.RowPercents.Add(((_multiplier * (row + 1)) / rows) - ((_multiplier * row) / rows));
            }

            for (int col = 0; col < cols; col++)
            {
                _gridModel.ColumnPercents.Add(((_multiplier * (col + 1)) / cols) - ((_multiplier * col) / cols));
            }

            int index = ZoneCount - 1;

            for (int col = cols - 1; col >= 0; col--)
            {
                for (int row = rows - 1; row >= 0; row--)
                {
                    _gridModel.CellChildMap[row, col] = index--;
                    if (index < 0)
                    {
                        index = 0;
                    }
                }
            }

            // Update the "Priority Grid" Default Layout
            if (ZoneCount <= _priorityData.Length)
            {
                _priorityGridModel.Reload(_priorityData[ZoneCount - 1]);
            }
            else
            {
                // same as grid;
                _priorityGridModel.Rows           = _gridModel.Rows;
                _priorityGridModel.Columns        = _gridModel.Columns;
                _priorityGridModel.RowPercents    = _gridModel.RowPercents;
                _priorityGridModel.ColumnPercents = _gridModel.ColumnPercents;
                _priorityGridModel.CellChildMap   = _gridModel.CellChildMap;
            }
        }
Пример #23
0
            static void ErasePixel(MouseEventArgs e)
            {
                byte[] ColorData = { 0, 0, 0, 0 }; // B G R

                Int32Rect rect = new Int32Rect(
                        (int)(e.GetPosition(i).X),
                        (int)(e.GetPosition(i).Y),
                        1,
                        1);

                writeableBitmap.WritePixels(rect, ColorData, 4, 0);
            }
Пример #24
0
 public byte[] GetRectangle(Int32Rect rect)
 {
     return(GetRectangle(rect, _buffer));
 }
Пример #25
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            int count = 0;
            var title = default(string);

            while (running)
            {
                using (var transformedDepth = new Image(ImageFormat.Depth16, colorWidth, colorHeight, colorWidth * sizeof(UInt16)))
                    using (var capture = await Task.Run(() => { return(this.kinect.GetCapture()); }))
                    {
                        count++;

                        this.transform.DepthImageToColorCamera(capture, transformedDepth);

                        this.bitmap.Lock();

                        var color  = capture.Color;
                        var region = new Int32Rect(0, 0, color.WidthPixels, color.HeightPixels);

                        unsafe
                        {
                            using (var pin = color.Memory.Pin())
                            {
                                this.bitmap.WritePixels(region, (IntPtr)pin.Pointer, (int)color.Size, color.StrideBytes);
                            }

                            if (boundingBox != null)
                            {
                                int y = (boundingBox.Y + boundingBox.H / 2);
                                int x = (boundingBox.X + boundingBox.W / 2);

                                this.StatusText = $"The {title} is: {transformedDepth.GetPixel<ushort>(y, x)} mm away";

                                this.Outline.Width  = boundingBox.W;
                                this.Outline.Height = boundingBox.H;
                                this.Outline.SetValue(Canvas.LeftProperty, boundingBox.X / this.CompositeImage.ActualWidth * this.ImageView.ActualWidth);
                                this.Outline.SetValue(Canvas.TopProperty, boundingBox.Y / this.CompositeImage.ActualHeight * this.ImageView.ActualHeight);
                            }
                        }

                        this.bitmap.AddDirtyRect(region);
                        this.bitmap.Unlock();

                        if (count % 30 == 0)
                        {
                            running = false;

                            var stream = StreamFromBitmapSource(this.bitmap);
                            var text   = await computerVision.RecognizePrintedTextInStreamAsync(true, stream, OcrLanguages.En);

                            if (text != null)
                            {
                                foreach (var textRegion in text.Regions)
                                {
                                    if (textRegion.Lines != null && textRegion.Lines.Any())
                                    {
                                        foreach (var line in textRegion.Lines)
                                        {
                                            Console.WriteLine(string.Join(" ", line.Words.Select(w => w.Text)));
                                        }
                                    }
                                }
                            }
                            // title = await AnalyzeImage().ConfigureAwait(false);

                            running = true;
                        }
                    }
            }
        }
Пример #26
0
        private void SaveFrame(SafeMILHandle frameEncodeHandle, SafeMILHandle encoderOptions, BitmapFrame frame)
        {
            SetupFrame(frameEncodeHandle, encoderOptions);

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeInitialized;

            // Set the size
            HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetSize(
                              frameEncodeHandle,
                              frame.PixelWidth,
                              frame.PixelHeight
                              ));

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeSizeSet;

            // Set the resolution
            double dpiX = frame.DpiX;
            double dpiY = frame.DpiY;

            if (dpiX <= 0)
            {
                dpiX = 96;
            }
            if (dpiY <= 0)
            {
                dpiY = 96;
            }

            HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetResolution(
                              frameEncodeHandle,
                              dpiX,
                              dpiY
                              ));

            // Helpful for debugging stress and remote dumps
            _encodeState = EncodeState.FrameEncodeResolutionSet;

            if (_supportsFrameThumbnails)
            {
                // Set the thumbnail.
                BitmapSource thumbnail = frame.Thumbnail;

                if (thumbnail != null)
                {
                    SafeMILHandle thumbnailHandle = thumbnail.WicSourceHandle;

                    lock (thumbnail.SyncObject)
                    {
                        HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.SetThumbnail(
                                          frameEncodeHandle,
                                          thumbnailHandle
                                          ));

                        // Helpful for debugging stress and remote dumps
                        _encodeState = EncodeState.FrameEncodeThumbnailSet;
                    }
                }
            }

            // if the source has been color corrected, we want to use a corresponding color profile
            if (frame._isColorCorrected)
            {
                ColorContext colorContext     = new ColorContext(frame.Format);
                IntPtr[]     colorContextPtrs = new IntPtr[1] {
                    colorContext.ColorContextHandle.DangerousGetHandle()
                };

                int hr = UnsafeNativeMethods.WICBitmapFrameEncode.SetColorContexts(
                    frameEncodeHandle,
                    1,
                    colorContextPtrs
                    );

                // It's possible that some encoders may not support color contexts so don't check hr
                if (hr == HRESULT.S_OK)
                {
                    // Helpful for debugging stress and remote dumps
                    _encodeState = EncodeState.FrameEncodeColorContextsSet;
                }
            }
            // if the caller has explicitly provided color contexts, add them to the encoder
            else
            {
                IList <ColorContext> colorContexts = frame.ColorContexts;
                if (colorContexts != null && colorContexts.Count > 0)
                {
                    int count = colorContexts.Count;

                    // Marshal can't convert SafeMILHandle[] so we must
                    {
                        IntPtr[] colorContextPtrs = new IntPtr[count];
                        for (int i = 0; i < count; ++i)
                        {
                            colorContextPtrs[i] = colorContexts[i].ColorContextHandle.DangerousGetHandle();
                        }

                        int hr = UnsafeNativeMethods.WICBitmapFrameEncode.SetColorContexts(
                            frameEncodeHandle,
                            (uint)count,
                            colorContextPtrs
                            );

                        // It's possible that some encoders may not support color contexts so don't check hr
                        if (hr == HRESULT.S_OK)
                        {
                            // Helpful for debugging stress and remote dumps
                            _encodeState = EncodeState.FrameEncodeColorContextsSet;
                        }
                    }
                }
            }

            // Set the pixel format and palette

            lock (frame.SyncObject)
            {
                SafeMILHandle outSourceHandle    = new SafeMILHandle();
                SafeMILHandle bitmapSourceHandle = frame.WicSourceHandle;
                SafeMILHandle paletteHandle      = new SafeMILHandle();

                // Set the pixel format and palette of the bitmap.
                // This could (but hopefully won't) introduce a format converter.
                HRESULT.Check(UnsafeNativeMethods.WICCodec.WICSetEncoderFormat(
                                  bitmapSourceHandle,
                                  paletteHandle,
                                  frameEncodeHandle,
                                  out outSourceHandle
                                  ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeFormatSet;
                _writeSourceHandles.Add(outSourceHandle);

                // Set the metadata
                if (_supportsFrameMetadata)
                {
                    BitmapMetadata metadata = frame.Metadata as BitmapMetadata;

                    // If the frame has metadata associated with a different container format, then we ignore it.
                    if (metadata != null && metadata.GuidFormat == ContainerFormat)
                    {
                        SafeMILHandle /* IWICMetadataQueryWriter */ metadataHandle = new SafeMILHandle();

                        HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.GetMetadataQueryWriter(
                                          frameEncodeHandle,
                                          out metadataHandle
                                          ));

                        PROPVARIANT propVar = new PROPVARIANT();

                        try
                        {
                            propVar.Init(metadata);

                            lock (metadata.SyncObject)
                            {
                                HRESULT.Check(UnsafeNativeMethods.WICMetadataQueryWriter.SetMetadataByName(
                                                  metadataHandle,
                                                  "/",
                                                  ref propVar
                                                  ));

                                // Helpful for debugging stress and remote dumps
                                _encodeState = EncodeState.FrameEncodeMetadataSet;
                            }
                        }
                        finally
                        {
                            propVar.Clear();
                        }
                    }
                }

                Int32Rect r = new Int32Rect();
                HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.WriteSource(
                                  frameEncodeHandle,
                                  outSourceHandle,
                                  ref r
                                  ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeSourceWritten;

                HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.Commit(
                                  frameEncodeHandle
                                  ));

                // Helpful for debugging stress and remote dumps
                _encodeState = EncodeState.FrameEncodeCommitted;
            }
        }
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Tracker tracker = Tracker.Create(this.kinect.GetCalibration(), new TrackerConfiguration()
            {
                ProcessingMode = TrackerProcessingMode.Gpu, SensorOrientation = SensorOrientation.Default
            });

            while (running)
            {
                using (Capture capture = await Task.Run(() => { return(this.kinect.GetCapture()); }))
                {
                    this.StatusText = "Received Capture: " + capture.Depth.DeviceTimestamp;

                    this.bitmap.Lock();

                    var color  = capture.Color;
                    var region = new Int32Rect(0, 0, color.WidthPixels, color.HeightPixels);



                    unsafe
                    {
                        using (var pin = color.Memory.Pin())
                        {
                            this.bitmap.WritePixels(region, (IntPtr)pin.Pointer, (int)color.Size, color.StrideBytes);
                            var bmpSource = BitmapSource.Create(color.WidthPixels, color.HeightPixels, 96.0, 96.0, PixelFormats.Bgr32, null, color.Memory.ToArray(), color.StrideBytes);

                            // JpegBitmapEncoder to save BitmapSource to file
                            // imageSerial is the serial of the sequential image
                            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                            encoder.Frames.Add(BitmapFrame.Create(bmpSource));
                            using (var fs = new FileStream("./img/" + (imageSerial++) + ".jpeg", FileMode.Create, FileAccess.Write))
                            {
                                encoder.Save(fs);
                            }
                        }
                    }

                    this.bitmap.AddDirtyRect(region);
                    this.bitmap.Unlock();

                    tracker.EnqueueCapture(capture);
                }

                // Try getting latest tracker frame.
                using (Frame lastFrame = tracker.PopResult(TimeSpan.Zero, throwOnTimeout: false))
                {
                    if (lastFrame == null)
                    {
                        continue;
                    }
                    lock (lockObject)
                    {
                        List <Vector3> joints = new List <Vector3>();
                        for (uint i = 0; i < lastFrame.NumberOfBodies; ++i)
                        {
                            Skeleton skeleton = lastFrame.GetBodySkeleton(i);
                            var      bodyId   = lastFrame.GetBodyId(i);
                            for (int jointId = 0; jointId < (int)JointId.Count; ++jointId)
                            {
                                var joint = skeleton.GetJoint(jointId);
                                joints.Add(joint.Position / 1000);
                            }
                        }
                        jointsList.Add(joints);
                    }
                }
            }
        }
Пример #28
0
        protected override void CreateOrUpdateBitmap(bool isPopup, Rect dirtyRect, IntPtr buffer, int width, int height, Image image, ref Size currentSize, ref MemoryMappedFile mappedFile, ref MemoryMappedViewAccessor viewAccessor)
        {
            bool createNewBitmap = false;

            lock (lockObject)
            {
                int pixels        = width * height;
                int numberOfBytes = pixels * BytesPerPixel;

                createNewBitmap = mappedFile == null || currentSize.Height != height || currentSize.Width != width;

                if (createNewBitmap)
                {
                    //If the MemoryMappedFile is smaller than we need then create a larger one
                    //If it's larger then we need then rather than going through the costly expense of
                    //allocating a new one we'll just use the old one and only access the number of bytes we require.
                    if (viewAccessor == null || viewAccessor.Capacity < numberOfBytes)
                    {
                        ReleaseMemoryMappedView(ref mappedFile, ref viewAccessor);

                        mappedFile = MemoryMappedFile.CreateNew(null, numberOfBytes, MemoryMappedFileAccess.ReadWrite);

                        viewAccessor = mappedFile.CreateViewAccessor();
                    }

                    currentSize.Height = height;
                    currentSize.Width  = width;
                }

                NativeMethodWrapper.MemoryCopy(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, numberOfBytes);

                //Take a reference to the sourceBuffer that's used to update our WritableBitmap,
                //once we're on the UI thread we need to check if it's still valid
                var sourceBuffer = viewAccessor.SafeMemoryMappedViewHandle;

                image.Dispatcher.BeginInvoke((Action)(() =>
                {
                    lock (lockObject)
                    {
                        if (sourceBuffer.IsClosed || sourceBuffer.IsInvalid)
                        {
                            return;
                        }

                        if (createNewBitmap)
                        {
                            if (image.Source != null)
                            {
                                image.Source = null;
                                GC.Collect(1);
                            }

                            image.Source = new WriteableBitmap(width, height, dpiX, dpiY, PixelFormat, null);
                        }

                        var stride = width * BytesPerPixel;
                        var noOfBytes = stride * height;

                        var bitmap = (WriteableBitmap)image.Source;

                        //By default we'll only update the dirty rect, for those that run into a MILERR_WIN32ERROR Exception (#2035)
                        //it's desirably to either upgrade to a newer .Net version (only client runtime needs to be installed, not compiled
                        //against a newer version. Or invalidate the whole bitmap
                        if (invalidateDirtyRect)
                        {
                            // Update the dirty region
                            var sourceRect = new Int32Rect(dirtyRect.X, dirtyRect.Y, dirtyRect.Width, dirtyRect.Height);

                            bitmap.Lock();
                            bitmap.WritePixels(sourceRect, sourceBuffer.DangerousGetHandle(), noOfBytes, stride, dirtyRect.X, dirtyRect.Y);
                            bitmap.Unlock();
                        }
                        else
                        {
                            // Update whole bitmap
                            var sourceRect = new Int32Rect(0, 0, width, height);

                            bitmap.Lock();
                            bitmap.WritePixels(sourceRect, sourceBuffer.DangerousGetHandle(), noOfBytes, stride);
                            bitmap.Unlock();
                        }
                    }
                }), dispatcherPriority);
            }
        }
Пример #29
0
 public TileTextureItem(int textureId, Int32Rect rect, BitmapSource bitmap)
 {
     TextureId = textureId;
     Bitmap    = bitmap;
     Rectangle = rect;
 }
Пример #30
0
        // UpdateLayoutModels
        //  Update the five default layouts based on the new ZoneCount
        private void UpdateLayoutModels()
        {
            int previousZoneCount = _focusModel.Zones.Count;

            // Update the "Focus" Default Layout
            _focusModel.Zones.Clear();

            Int32Rect focusZoneRect       = new Int32Rect((int)(_focusModel.ReferenceWidth * 0.1), (int)(_focusModel.ReferenceHeight * 0.1), (int)(_focusModel.ReferenceWidth * 0.6), (int)(_focusModel.ReferenceHeight * 0.6));
            int       focusRectXIncrement = (ZoneCount <= 1) ? 0 : (int)(_focusModel.ReferenceWidth * 0.2) / (ZoneCount - 1);
            int       focusRectYIncrement = (ZoneCount <= 1) ? 0 : (int)(_focusModel.ReferenceHeight * 0.2) / (ZoneCount - 1);

            for (int i = 0; i < ZoneCount; i++)
            {
                _focusModel.Zones.Add(focusZoneRect);
                focusZoneRect.X += focusRectXIncrement;
                focusZoneRect.Y += focusRectYIncrement;
            }

            // Update the "Rows" and "Columns" Default Layouts
            // They can share their model, just transposed
            _rowsModel.CellChildMap    = new int[ZoneCount, 1];
            _columnsModel.CellChildMap = new int[1, ZoneCount];
            _rowsModel.Rows            = _columnsModel.Columns = ZoneCount;
            _rowsModel.RowPercents     = _columnsModel.ColumnPercents = new int[ZoneCount];

            for (int i = 0; i < ZoneCount; i++)
            {
                _rowsModel.CellChildMap[i, 0]    = i;
                _columnsModel.CellChildMap[0, i] = i;
                _rowsModel.RowPercents[i]        = c_multiplier / ZoneCount; // _columnsModel is sharing the same array
            }

            // Update the "Grid" Default Layout
            int rows       = 1;
            int cols       = 1;
            int mergeCount = 0;

            while (ZoneCount / rows >= rows)
            {
                rows++;
            }
            rows--;
            cols = ZoneCount / rows;
            if (ZoneCount % rows == 0)
            {
                // even grid
            }
            else
            {
                cols++;
                mergeCount = rows - (ZoneCount % rows);
            }
            _gridModel.Rows           = rows;
            _gridModel.Columns        = cols;
            _gridModel.RowPercents    = new int[rows];
            _gridModel.ColumnPercents = new int[cols];
            _gridModel.CellChildMap   = new int[rows, cols];

            for (int row = 0; row < rows; row++)
            {
                _gridModel.RowPercents[row] = c_multiplier / rows;
            }

            for (int col = 0; col < cols; col++)
            {
                _gridModel.ColumnPercents[col] = c_multiplier / cols;
            }

            int index = 0;

            for (int col = cols - 1; col >= 0; col--)
            {
                for (int row = rows - 1; row >= 0; row--)
                {
                    _gridModel.CellChildMap[row, col] = index++;
                    if (index == ZoneCount)
                    {
                        index--;
                    }
                }
            }

            // Update the "Priority Grid" Default Layout
            if (ZoneCount <= s_priorityData.Length)
            {
                _priorityGridModel.Reload(s_priorityData[ZoneCount - 1]);
            }
            else
            {
                // same as grid;
                _priorityGridModel.Rows           = _gridModel.Rows;
                _priorityGridModel.Columns        = _gridModel.Columns;
                _priorityGridModel.RowPercents    = _gridModel.RowPercents;
                _priorityGridModel.ColumnPercents = _gridModel.ColumnPercents;
                _priorityGridModel.CellChildMap   = _gridModel.CellChildMap;
            }
        }
Пример #31
0
        /// <summary>
        /// Crops a given image.
        /// </summary>
        /// <param name="source">The BitmapSource.</param>
        /// <param name="rect">The crop rectangle.</param>
        /// <returns>The Cropped image.</returns>
        public static BitmapFrame CropImage(BitmapSource source, Int32Rect rect)
        {
            var croppedImage = new CroppedBitmap(source, rect);

            return(BitmapFrame.Create(croppedImage));
        }
Пример #32
0
        private void UpdateTiles(object sender, object e)
        {
            updateTimer.Stop();

            var zoom = (int)Math.Floor(zoomLevel + zoomLevelSwitchDelta);
            var transform = GetTileIndexMatrix(1 << zoom);

            // tile indices of visible rectangle
            var p1 = transform.Transform(new Point(0d, 0d));
            var p2 = transform.Transform(new Point(viewportSize.Width, 0d));
            var p3 = transform.Transform(new Point(0d, viewportSize.Height));
            var p4 = transform.Transform(new Point(viewportSize.Width, viewportSize.Height));

            // index ranges of visible tiles
            var x1 = (int)Math.Floor(Math.Min(p1.X, Math.Min(p2.X, Math.Min(p3.X, p4.X))));
            var y1 = (int)Math.Floor(Math.Min(p1.Y, Math.Min(p2.Y, Math.Min(p3.Y, p4.Y))));
            var x2 = (int)Math.Floor(Math.Max(p1.X, Math.Max(p2.X, Math.Max(p3.X, p4.X))));
            var y2 = (int)Math.Floor(Math.Max(p1.Y, Math.Max(p2.Y, Math.Max(p3.Y, p4.Y))));
            var grid = new Int32Rect(x1, y1, x2 - x1 + 1, y2 - y1 + 1);

            if (tileZoomLevel != zoom || tileGrid != grid || tileRotation != rotation)
            {
                tileZoomLevel = zoom;
                tileGrid = grid;
                tileRotation = rotation;

                UpdateRenderTransform();

                foreach (TileLayer tileLayer in InternalChildren)
                {
                    tileLayer.UpdateTiles(tileZoomLevel, tileGrid, (int)rotation);
                }
            }
        }
Пример #33
0
        internal InteropBitmap(IntPtr hicon, Int32Rect sourceRect, BitmapSizeOptions sizeOptions)
            : base(true) // Use virtuals
        {
            SecurityHelper.DemandUnmanagedCode();

            _bitmapInit.BeginInit();

            using (FactoryMaker myFactory = new FactoryMaker())
            {
                HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromHICON(
                    myFactory.ImagingFactoryPtr,
                    hicon,
                    out _unmanagedSource));
                Debug.Assert (_unmanagedSource != null && !_unmanagedSource.IsInvalid);
            }

            _unmanagedSource.CalculateSize();
            _sourceRect = sourceRect;
            _sizeOptions = sizeOptions;
            _syncObject = _unmanagedSource;

            _bitmapInit.EndInit();

            FinalizeCreation();
        }
Пример #34
0
        protected void UpdateTileRect()
        {
            updateTimer.Stop();

            if (parentMap != null)
            {
                var zoomLevel = (int)Math.Round(parentMap.ZoomLevel + ZoomLevelOffset);
                var transform = GetTileIndexMatrix(zoomLevel);

                // tile indices of visible rectangle
                var p1 = transform.Transform(new Point(0d, 0d));
                var p2 = transform.Transform(new Point(parentMap.RenderSize.Width, 0d));
                var p3 = transform.Transform(new Point(0d, parentMap.RenderSize.Height));
                var p4 = transform.Transform(new Point(parentMap.RenderSize.Width, parentMap.RenderSize.Height));

                // index ranges of visible tiles
                var x1 = (int)Math.Floor(Math.Min(p1.X, Math.Min(p2.X, Math.Min(p3.X, p4.X))));
                var y1 = (int)Math.Floor(Math.Min(p1.Y, Math.Min(p2.Y, Math.Min(p3.Y, p4.Y))));
                var x2 = (int)Math.Floor(Math.Max(p1.X, Math.Max(p2.X, Math.Max(p3.X, p4.X))));
                var y2 = (int)Math.Floor(Math.Max(p1.Y, Math.Max(p2.Y, Math.Max(p3.Y, p4.Y))));
                var rect = new Int32Rect(x1, y1, x2 - x1 + 1, y2 - y1 + 1);

                if (TileZoomLevel != zoomLevel || TileRect != rect)
                {
                    TileZoomLevel = zoomLevel;
                    TileRect = rect;

                    SetRenderTransform();
                    UpdateTiles(false);
                }
            }
        }
        /// <summary>
        /// BitmapSourceをMatに変換する.
        /// </summary>
        /// <param name="src">変換するBitmapSource</param>
        /// <param name="dst">出力先のMat</param>
#else
        /// <summary>
        /// Converts BitmapSource to Mat
        /// </summary>
        /// <param name="src">Input BitmapSource</param>
        /// <param name="dst">Output Mat</param>
#endif
        public static void ToMat(this BitmapSource src, Mat dst)
        {
            if (src == null)
            {
                throw new ArgumentNullException(nameof(src));
            }
            if (dst == null)
            {
                throw new ArgumentNullException(nameof(dst));
            }
            if (src.PixelWidth != dst.Width || src.PixelHeight != dst.Height)
            {
                throw new ArgumentException("size of src must be equal to size of dst");
            }
            if (dst.Dims > 2)
            {
                throw new ArgumentException("Mat dimensions must be 2");
            }

            int w        = src.PixelWidth;
            int h        = src.PixelHeight;
            int bpp      = src.Format.BitsPerPixel;
            int channels = WriteableBitmapConverter.GetOptimumChannels(src.Format);

            if (dst.Channels() != channels)
            {
                throw new ArgumentException("nChannels of dst is invalid", nameof(dst));
            }

            bool submat     = dst.IsSubmatrix();
            bool continuous = dst.IsContinuous();

            unsafe
            {
                byte *p    = (byte *)(dst.Data);
                long  step = dst.Step();

                // 1bppは手作業でコピー
                if (bpp == 1)
                {
                    if (submat)
                    {
                        throw new NotImplementedException("submatrix not supported");
                    }

                    // BitmapImageのデータを配列にコピー
                    // 要素1つに横8ピクセル分のデータが入っている。
                    int    stride = (w / 8) + 1;
                    byte[] pixels = new byte[h * stride];
                    src.CopyPixels(pixels, stride, 0);
                    int x = 0;
                    for (int y = 0; y < h; y++)
                    {
                        int offset = y * stride;
                        // この行の各バイトを調べていく
                        for (int bytePos = 0; bytePos < stride; bytePos++)
                        {
                            if (x < w)
                            {
                                // 現在の位置のバイトからそれぞれのビット8つを取り出す
                                byte b = pixels[offset + bytePos];
                                for (int i = 0; i < 8; i++)
                                {
                                    if (x >= w)
                                    {
                                        break;
                                    }
                                    p[step * y + x] = ((b & 0x80) == 0x80) ? (byte)255 : (byte)0;
                                    b <<= 1;
                                    x++;
                                }
                            }
                        }
                        // 次の行へ
                        x = 0;
                    }
                }
                // 8bpp

                /*else if (bpp == 8)
                 * {
                 *  int stride = w;
                 *  byte[] pixels = new byte[h * stride];
                 *  src.CopyPixels(pixels, stride, 0);
                 *  for (int y = 0; y < h; y++)
                 *  {
                 *      for (int x = 0; x < w; x++)
                 *      {
                 *          p[step * y + x] = pixels[y * stride + x];
                 *      }
                 *  }
                 * }*/
                // 24bpp, 32bpp, ...
                else
                {
                    int stride = w * ((bpp + 7) / 8);
                    if (!submat && continuous)
                    {
                        long imageSize = dst.DataEnd.ToInt64() - dst.Data.ToInt64();
                        if (imageSize < 0)
                        {
                            throw new OpenCvSharpException("The mat has invalid data pointer");
                        }
                        if (imageSize > int.MaxValue)
                        {
                            throw new OpenCvSharpException("Too big mat data");
                        }
                        src.CopyPixels(Int32Rect.Empty, dst.Data, (int)imageSize, stride);
                    }
                    else
                    {
                        // 高さ1pxの矩形ごと(≒1行ごと)にコピー
                        var roi = new Int32Rect {
                            X = 0, Y = 0, Width = w, Height = 1
                        };
                        IntPtr dstData = dst.Data;
                        for (int y = 0; y < h; y++)
                        {
                            roi.Y = y;
                            src.CopyPixels(roi, dstData, stride, stride);
                            dstData = new IntPtr(dstData.ToInt64() + stride);
                        }
                    }
                }
            }
        }
Пример #36
0
        public void Load(object sender, RoutedEventArgs e)
        {
            const string filename = "save.txt";

            try
            {
                var reader = new StreamReader(filename);

                string firstLine  = reader.ReadLine();
                string secondLine = reader.ReadLine();
                timeCountdown      = int.Parse(firstLine);
                CountdownTime.Text = firstLine;
                var source = new BitmapImage(
                    new Uri(secondLine, UriKind.RelativeOrAbsolute));
                previewImage.Width  = 300;
                previewImage.Height = 300;
                previewImage.Source = source;

                // Bat dau cat thanh 9 manh
                int count = 0;
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        if (!((i == 2) && (j == 2)))
                        {
                            TransformedBitmap mybitmapIMG;
                            if (source.Height > source.Width)
                            {
                                double scaleTransfH = 300 / source.Height;
                                mybitmapIMG = new TransformedBitmap(source, new ScaleTransform(scaleTransfH, scaleTransfH));
                                imgWidth    = (int)(mybitmapIMG.PixelWidth / 3);
                                imgHeight   = (int)(mybitmapIMG.PixelHeight / 3);
                            }
                            else
                            {
                                double scaleTransfW = 300 / source.Width;
                                mybitmapIMG = new TransformedBitmap(source, new ScaleTransform(scaleTransfW, scaleTransfW));
                                imgWidth    = (int)(mybitmapIMG.PixelWidth / 3);
                                imgHeight   = (int)(mybitmapIMG.PixelHeight / 3);
                            }
                            drawLines(startX, startY, imgWidth, imgHeight);
                            var rect       = new Int32Rect(j * imgWidth, i * imgHeight, imgWidth, imgHeight);
                            var cropBitmap = new CroppedBitmap(mybitmapIMG,
                                                               rect);
                            var cropImage = new Image();
                            cropImage.Stretch = Stretch.Fill;
                            cropImage.Width   = imgWidth;
                            cropImage.Height  = imgHeight;
                            cropImage.Source  = cropBitmap;
                            canvas.Children.Add(cropImage);
                            Canvas.SetLeft(cropImage, startX + j * (imgWidth + 2));
                            Canvas.SetTop(cropImage, startY + i * (imgHeight + 2));
                            cropImage.MouseLeftButtonDown      += CropImage_MouseLeftButtonDown;
                            cropImage.PreviewMouseLeftButtonUp += CropImage_MouseLeftButtonUp;
                            cropImage.Tag  = new Tuple <int, int>(i, j);
                            cropImage.Name = $"s{count}";
                            listCropImg.Add(cropImage);
                            count++;
                        }
                    }
                }
                Image nullImage = new Image();
                listCropImg.Add(nullImage);
                int i2      = 0;
                int j2      = 0;
                int irndIMG = 0;
                int jrndIMG = 0;
                int rndIMG;
                for (int a = 0; a < 9; a++)
                {
                    string nameIMG = reader.ReadLine();

                    if (nameIMG != "")
                    {
                        rndIMG = int.Parse(nameIMG.Substring(nameIMG.Length - 1, 1));
                    }
                    else
                    {
                        rndIMG = 8;
                    }
                    if (j2 == 3)
                    {
                        j2 = 0;
                        i2++;
                    }

                    switch (rndIMG)
                    {
                    case 0:
                        irndIMG = 0;
                        jrndIMG = 0;
                        break;

                    case 1:
                        irndIMG = 0;
                        jrndIMG = 1;
                        break;

                    case 2:
                        irndIMG = 0;
                        jrndIMG = 2;
                        break;

                    case 3:
                        irndIMG = 1;
                        jrndIMG = 0;
                        break;

                    case 4:
                        irndIMG = 1;
                        jrndIMG = 1;
                        break;

                    case 5:
                        irndIMG = 1;
                        jrndIMG = 2;
                        break;

                    case 6:
                        irndIMG = 2;
                        jrndIMG = 0;
                        break;

                    case 7:
                        irndIMG = 2;
                        jrndIMG = 1;
                        break;

                    case 8:
                        irndIMG = 2;
                        jrndIMG = 2;
                        iFree   = i2;
                        jFree   = j2;
                        break;
                    }
                    Canvas.SetLeft(listCropImg[rndIMG], startX + j2 * imgWidth + 2 * j2);
                    Canvas.SetTop(listCropImg[rndIMG], startY + i2 * imgHeight + 2 * i2);
                    Canvas.SetLeft(listCropImg[a], startX + jrndIMG * imgWidth + 2 * jrndIMG);
                    Canvas.SetTop(listCropImg[a], startY + irndIMG * imgHeight + 2 * irndIMG);
                    listCropImg[a].Tag      = new Tuple <int, int>(irndIMG, jrndIMG);
                    listCropImg[rndIMG].Tag = new Tuple <int, int>(i2, j2);
                    Image imgtemp = new Image();
                    imgtemp             = listCropImg[a];
                    listCropImg[a]      = listCropImg[rndIMG];
                    listCropImg[rndIMG] = imgtemp;
                    j2++;
                }
                MessageBox.Show("Game đã được load!!!");
                dt.Start();
                _isGamePLaying = true;
            }
            catch
            {
                MessageBox.Show("Không thể load game gần nhất!!!\nBạn chưa lưu game hoặc file ảnh đã bị thay đổi!");
                this.Window_Loaded(sender, e);
            }
        }
Пример #37
0
        internal void UpdateTiles(int zoomLevel, Int32Rect grid, int rotation)
        {
            this.grid = grid;
            this.zoomLevel = zoomLevel;
            this.rotation = SupportsRotation ? rotation : 0;

            if (tileSource != null)
            {
                tileImageLoader.CancelGetTiles();
                SelectTiles();
                RenderTiles();
                tileImageLoader.BeginGetTiles(this, tiles.Where(t => !t.HasImageSource));
            }
        }
Пример #38
0
 public static extern bool GetClientRect(IntPtr hWnd, out Int32Rect lpRect);
 internal static extern bool GetClientRect(IntPtr windowHandle, out Int32Rect clientRect);
 internal static extern bool ClientToScreen(IntPtr windowHandle, ref Int32Rect point);
Пример #41
0
            int IWICBitmapSource.CopyPixels(IntPtr prc, int cbStride, int cbPixels, IntPtr pvPixels)
            {
                if (cbStride < 0)
                {
                    return NativeMethods.E_INVALIDARG;
                }

                if (pvPixels == IntPtr.Zero)
                {
                    return NativeMethods.E_INVALIDARG;
                }

                BitmapSource bitmapSource;
                if(_bitmapSource.TryGetTarget(out bitmapSource))
                {
                    Int32Rect rc;
                    
                    if (prc == IntPtr.Zero)
                    {
                        rc = new Int32Rect(0, 0, bitmapSource.PixelWidth, bitmapSource.PixelHeight);
                    }
                    else
                    {
                        rc = (Int32Rect)Marshal.PtrToStructure(prc, typeof(Int32Rect));
                    }
                    
                    int rectHeight, rectWidth;
                    
                    rectHeight = rc.Height;
                    rectWidth = rc.Width;
                    
                    if (rc.Width < 1 || rc.Height < 1)
                    {
                        return NativeMethods.E_INVALIDARG;
                    }
                    
                    // assuming cbStride can't be negative, but that prc.Height can
                    PixelFormat pfStruct = bitmapSource.Format;
                    
                    if (pfStruct.Format == PixelFormatEnum.Default ||
                        pfStruct.Format == PixelFormatEnum.Extended)
                    {
                        return (int)(WinCodecErrors.WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT);
                    }
                    
                    
                    int rectRowSize = checked((rectWidth * pfStruct.InternalBitsPerPixel + 7) / 8);
                    
                    if (cbPixels < checked((rectHeight - 1) * cbStride + rectRowSize))
                    {
                        return (int)(WinCodecErrors.WINCODEC_ERR_INSUFFICIENTBUFFER);
                    }
                    
                    // Need to marshal
                    int arraySize = checked(rectHeight * rectRowSize);
                    byte[] managedArray = new byte[arraySize];
                    
                    // perform the copy
                    bitmapSource.CopyPixels(rc, managedArray, rectRowSize, 0);
                    
                    {
                        // transfer the contents of the relevant rect from the managed array to pvPixels
                        long rowPtr = pvPixels.ToInt64();
                        for (int y = 0; y < rectHeight; y++)
                        {
                            Marshal.Copy(managedArray, y * rectRowSize, new IntPtr(rowPtr), rectRowSize);
                            rowPtr += cbStride;
                        }
                    }
                    
                    return NativeMethods.S_OK;
                }
                else
                {
                    return NativeMethods.E_FAIL;
                }
            }
Пример #42
0
        private static void copyBitmap(BitmapSource source, WriteableBitmap target, bool dispatcher, int spacing, bool freezeBitmap)
        {
            int width  = source.PixelWidth;
            int height = source.PixelHeight;
            int stride = width * ((source.Format.BitsPerPixel + 7) / 8);

            byte[] bits = new byte[height * stride];
            source.CopyPixels(bits, stride, 0);
            source = null;

            //original code.
            //writeBitmap.Dispatcher.Invoke(DispatcherPriority.Background,
            //    new ThreadStart(delegate
            //    {
            //        //UI Thread
            //        Int32Rect outRect = new Int32Rect(0, (int)(writeBitmap.Height - height) / 2, width, height);
            //        writeBitmap.WritePixels(outRect, bits, stride, 0);
            //    }));

            //Bugfixes by h32

            if (dispatcher)
            {
                target.Dispatcher.BeginInvoke(DispatcherPriority.Background,
                                              new ThreadStart(delegate
                {
                    //UI Thread
                    var delta         = target.Height - height;
                    var newWidth      = width > target.Width ? (int)target.Width : width;
                    var newHeight     = height > target.Height ? (int)target.Height : height;
                    Int32Rect outRect = new Int32Rect((int)((target.Width - newWidth) / 2), (int)(delta >= 0 ? delta : 0) / 2 + spacing, newWidth - (spacing * 2), newWidth - (spacing * 2));
                    try
                    {
                        target.WritePixels(outRect, bits, stride, 0);
                        if (freezeBitmap)
                        {
                            target.Freeze();
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debugger.Break();
                    }
                }));
            }
            else
            {
                var       delta     = target.Height - height;
                var       newWidth  = width > target.Width ? (int)target.Width : width;
                var       newHeight = height > target.Height ? (int)target.Height : height;
                Int32Rect outRect   = new Int32Rect(spacing, (int)(delta >= 0 ? delta : 0) / 2 + spacing, newWidth - (spacing * 2), newWidth - (spacing * 2));
                try
                {
                    target.WritePixels(outRect, bits, stride, 0);
                    if (freezeBitmap)
                    {
                        target.Freeze();
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debugger.Break();
                }
            }
        }
Пример #43
0
        public virtual void CopyPixels(Int32Rect sourceRect, IntPtr buffer, int bufferSize, int stride)
        {
            ReadPreamble();
            EnsureShouldUseVirtuals();
            _bitmapInit.EnsureInitializedComplete();
            CompleteDelayedCreation();

            // Demand Site Of origin on the URI if it passes then this  information is ok to expose
            CheckIfSiteOfOrigin();

            CriticalCopyPixels(sourceRect, buffer, bufferSize, stride);
        }
Пример #44
0
        public MainWindow()
        {
            InitializeComponent();

            // Open Device
            device = K4A.Device.Open();

            // Start Cameras
            device.StartCameras(new K4A.DeviceConfiguration
            {
                ColorFormat            = K4A.ImageFormat.ColorBGRA32,
                ColorResolution        = K4A.ColorResolution.R720p,
                DepthMode              = K4A.DepthMode.NFOV_2x2Binned,
                SynchronizedImagesOnly = true
            });

            // Get Calibration
            calibration = device.GetCalibration(K4A.DepthMode.NFOV_2x2Binned, K4A.ColorResolution.R720p);

            // Create Tracker
            tracker = K4ABT.Tracker.Create(
                calibration,
                new K4ABT.TrackerConfiguration
            {
                SensorOrientation = K4ABT.SensorOrientation.Default,
                ProcessingMode    = K4ABT.TrackerProcessingMode.Gpu
            }
                );

            // Create Buffer
            int color_width  = calibration.ColorCameraCalibration.ResolutionWidth;
            int color_height = calibration.ColorCameraCalibration.ResolutionHeight;

            const int color_channles = 4;

            color_stride = color_width * sizeof(byte) * color_channles;
            color_rect   = new Int32Rect(0, 0, color_width, color_height);
            color_bitmap = new WriteableBitmap(color_width, color_height, 96.0, 96.0, PixelFormats.Bgra32, null);

            // Generate Color LUT
            colors    = new Color[6];
            colors[0] = new Color()
            {
                B = 255, G = 0, R = 0, A = 128
            };
            colors[1] = new Color()
            {
                B = 0, G = 255, R = 0, A = 128
            };
            colors[2] = new Color()
            {
                B = 0, G = 0, R = 255, A = 128
            };
            colors[3] = new Color()
            {
                B = 255, G = 255, R = 0, A = 128
            };
            colors[4] = new Color()
            {
                B = 0, G = 255, R = 255, A = 128
            };
            colors[5] = new Color()
            {
                B = 255, G = 0, R = 255, A = 128
            };

            // Bined Image Control
            Color_Image.Source = color_bitmap;
            Color_Image.Width  = color_width;
            Color_Image.Height = color_height;

            // Set Cnvas Size
            Canvas_Body.Width  = color_width;
            Canvas_Body.Height = color_height;
        }
Пример #45
0
        internal void CriticalCopyPixels(Int32Rect sourceRect, IntPtr buffer, int bufferSize, int stride)
        {
            if (buffer == IntPtr.Zero)
                throw new ArgumentNullException("buffer");

            if (stride <= 0)
                throw new ArgumentOutOfRangeException("stride", SR.Get(SRID.ParameterMustBeGreaterThanZero));

            if (sourceRect.Width <= 0)
                sourceRect.Width = PixelWidth;

            if (sourceRect.Height <= 0)
                sourceRect.Height = PixelHeight;

            if (sourceRect.Width > PixelWidth)
                throw new ArgumentOutOfRangeException("sourceRect.Width", SR.Get(SRID.ParameterCannotBeGreaterThan, PixelWidth));

            if (sourceRect.Height > PixelHeight)
                throw new ArgumentOutOfRangeException("sourceRect.Height", SR.Get(SRID.ParameterCannotBeGreaterThan, PixelHeight));

            int minStride = checked(((sourceRect.Width * Format.BitsPerPixel) + 7) / 8);
            if (stride < minStride)
                throw new ArgumentOutOfRangeException("stride", SR.Get(SRID.ParameterCannotBeLessThan, minStride));

            int minRequiredDestSize = checked((stride * (sourceRect.Height - 1)) + minStride);
            if (bufferSize < minRequiredDestSize)
                throw new ArgumentOutOfRangeException("buffer", SR.Get(SRID.ParameterCannotBeLessThan, minRequiredDestSize));

            lock (_syncObject)
            {
                HRESULT.Check(UnsafeNativeMethods.WICBitmapSource.CopyPixels(
                    WicSourceHandle,
                    ref sourceRect,
                    (uint)stride,
                    (uint)bufferSize,
                    buffer
                    ));
            }
        }
Пример #46
0
        public static WriteableBitmap ResizeWritableBitmap(this WriteableBitmap wBitmap, int reqWidth, int reqHeight)
        {
            int Stride = wBitmap.PixelWidth * ((wBitmap.Format.BitsPerPixel + 7) / 8);
            int NumPixels = Stride * wBitmap.PixelHeight;
            ushort[] ArrayOfPixels = new ushort[NumPixels];

            wBitmap.CopyPixels(ArrayOfPixels, Stride, 0);

            int OriWidth = (int)wBitmap.PixelWidth;
            int OriHeight = (int)wBitmap.PixelHeight;

            double nXFactor = (double)OriWidth / (double)reqWidth;
            double nYFactor = (double)OriHeight / (double)reqHeight;

            double fraction_x, fraction_y, one_minus_x, one_minus_y;
            int ceil_x, ceil_y, floor_x, floor_y;

            ushort pix1, pix2, pix3, pix4;
            int nStride = reqWidth * ((wBitmap.Format.BitsPerPixel + 7) / 8);
            int nNumPixels = reqWidth * reqHeight;
            ushort[] newArrayOfPixels = new ushort[nNumPixels];
            /*Core Part*/
            /* Code project article :
            Image Processing for Dummies with C# and GDI+ Part 2 - Convolution Filters By Christian Graus</a>

            href=<a href="http://www.codeproject.com/KB/GDI-plus/csharpfilters.aspx"></a>
            */
            for (int y = 0; y < reqHeight; y++)
            {
                for (int x = 0; x < reqWidth; x++)
                {
                    // Setup
                    floor_x = (int)Math.Floor(x * nXFactor);
                    floor_y = (int)Math.Floor(y * nYFactor);

                    ceil_x = floor_x + 1;
                    if (ceil_x >= OriWidth) ceil_x = floor_x;

                    ceil_y = floor_y + 1;
                    if (ceil_y >= OriHeight) ceil_y = floor_y;

                    fraction_x = x * nXFactor - floor_x;
                    fraction_y = y * nYFactor - floor_y;

                    one_minus_x = 1.0 - fraction_x;
                    one_minus_y = 1.0 - fraction_y;

                    pix1 = ArrayOfPixels[floor_x + floor_y * OriWidth];
                    pix2 = ArrayOfPixels[ceil_x + floor_y * OriWidth];
                    pix3 = ArrayOfPixels[floor_x + ceil_y * OriWidth];
                    pix4 = ArrayOfPixels[ceil_x + ceil_y * OriWidth];

                    ushort g1 = (ushort)(one_minus_x * pix1 + fraction_x * pix2);
                    ushort g2 = (ushort)(one_minus_x * pix3 + fraction_x * pix4);
                    ushort g = (ushort)(one_minus_y * (double)(g1) + fraction_y * (double)(g2));
                    newArrayOfPixels[y * reqWidth + x] = g;
                }
            }
            /*End of Core Part*/
            WriteableBitmap newWBitmap = new WriteableBitmap(reqWidth, reqHeight, 96, 96, PixelFormats.Gray16, null);
            Int32Rect Imagerect = new Int32Rect(0, 0, reqWidth, reqHeight);
            int newStride = reqWidth * ((PixelFormats.Gray16.BitsPerPixel + 7) / 8);
            newWBitmap.WritePixels(Imagerect, newArrayOfPixels, newStride, 0);
            return newWBitmap;
        }