示例#1
0
        public Image GetImage(float x, float y, float width, float height)
        {
            DatabaseIndex imageIndex = DatabaseManager.Instance.Indices.Find(idx => idx.InstanceId == this.TextureInstanceId && idx.TypeId == PropertyConstants.RasterImageType);

            if (imageIndex != null)
            {
                using (MemoryStream imageByteStream = new MemoryStream(imageIndex.GetIndexData(true)))
                {
                    if (bitmapCache == null)
                    {
                        RasterImage img = RasterImage.CreateFromStream(imageByteStream, RasterChannel.All);
                        bitmapCache = img.MipMaps[0];
                    }

                    float pxX      = (float)bitmapCache.Width * x;
                    float pxY      = (float)bitmapCache.Width * y;
                    float pxWidth  = (float)bitmapCache.Width * width;
                    float pxHeight = (float)bitmapCache.Width * height;

                    WriteableBitmap croppedImage = bitmapCache.Crop(new System.Windows.Rect(pxX, pxY, Math.Abs(pxWidth), Math.Abs(pxHeight)));

                    return(new Image()
                    {
                        Source = croppedImage, Stretch = Stretch.None
                    });
                }
            }
            return(null);
        }
示例#2
0
        private async void CropImage(bool wide = false)
        {
            IsCropEnabled = false;
            try
            {
                var             img           = wide ? _previewImageWide : _previewImageNormal;
                WriteableBitmap resizedBitmap = new WriteableBitmap(CropWidth, CropHeight);
                //if (img.UriSource == null)
                //await resizedBitmap.LoadAsync(_originaPickedStorageFile);
                /*else*/
                if (!img.UriSource.ToString().Contains("ms-appdata"))
                {
                    var imgFile = await SaveImage(img, wide);

                    await resizedBitmap.LoadAsync(imgFile);
                }
                else
                {
                    await resizedBitmap.LoadAsync(await StorageFile.GetFileFromApplicationUriAsync(img.UriSource));
                }

                if (wide)
                {
                    resizedBitmap = resizedBitmap.Crop(CropLeftWide, CropTopWide, CropWidthWide + CropLeftWide, CropTopWide + CropHeightWide);
                }
                else
                {
                    resizedBitmap = resizedBitmap.Crop(CropLeft, CropTop, CropWidth + CropLeft, CropTop + CropHeight);
                }

                var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync($"_cropTemp{(wide ? "Wide" : "")}.png", CreationCollisionOption.GenerateUniqueName);

                if (wide)
                {
                    _lastCroppedFileNameWide = file.Name;
                }
                else
                {
                    _lastCroppedFileName = file.Name;
                }

                await resizedBitmap.SaveAsync(file, BitmapEncoder.PngEncoderId);

                if (wide)
                {
                    PreviewImageWide = new BitmapImage(new Uri($"ms-appdata:///temp/{file.Name}"));
                }
                else
                {
                    PreviewImageNormal = new BitmapImage(new Uri($"ms-appdata:///temp/{file.Name}"));
                    UndoCropVisibility = Visibility.Visible;
                }
            }
            catch (Exception)
            {
                UWPUtilities.GiveStatusBarFeedback("An error occured...");
            }
            IsCropEnabled = true;
        }
示例#3
0
        private async void Crop()
        {
            double ratio = (double)wbOrigin.PixelWidth / image.ActualWidth;
            int    L     = (int)(clip_L * ratio);
            int    T     = (int)(clip_T * ratio);
            int    R     = (int)(clip_R * ratio);
            int    B     = (int)(clip_B * ratio);

            int width  = R - L;
            int height = B - T;

            WriteableBitmap wbNew = wbOrigin.Crop(L, T, width, height);

            App.CurrentInstance.wbForSingleMode = wbNew;
            Frame.Navigate(typeof(OperationPage), OperationPageType.Single);

            //IRandomAccessStream stream = new MemoryStream().AsRandomAccessStream();
            //await wbNew.ToStreamAsJpeg(stream);

            //byte[] buffer = wbNew.ToByteArray();// new byte[1];
            //IRandomAccessStream stream = new MemoryStream(buffer).AsRandomAccessStream();
            //BitmapImage bi = new BitmapImage();
            //bi.SetSource(stream);
            //resultImage.Visibility = Visibility.Visible;
            //resultImage.Source = bi;

            //return wbNew;
        }
示例#4
0
        public string Execute(FileItem item, string dest, ValuePairEnumerator configData)
        {
            var conf = new CropTransformViewModel(configData);

            using (MemoryStream fileStream = new MemoryStream(File.ReadAllBytes(item.FileName)))
            {
                BitmapDecoder bmpDec = BitmapDecoder.Create(fileStream,
                                                            BitmapCreateOptions.PreservePixelFormat,
                                                            BitmapCacheOption.OnLoad);
                WriteableBitmap writeableBitmap = BitmapFactory.ConvertToPbgra32Format(bmpDec.Frames[0]);
                if (conf.FromLiveView && ServiceProvider.DeviceManager.SelectedCameraDevice != null)
                {
                    var prop = ServiceProvider.DeviceManager.SelectedCameraDevice.LoadProperties();
                    conf.Left  = (int)(writeableBitmap.PixelWidth * prop.LiveviewSettings.HorizontalMin / 100);
                    conf.Width =
                        (int)
                        (writeableBitmap.PixelWidth *
                         (prop.LiveviewSettings.HorizontalMax - prop.LiveviewSettings.HorizontalMin) / 100);
                    conf.Top    = (int)(writeableBitmap.Height * prop.LiveviewSettings.VerticalMin / 100);
                    conf.Height =
                        (int)
                        (writeableBitmap.Height *
                         (prop.LiveviewSettings.VerticalMax - prop.LiveviewSettings.VerticalMin) / 100);
                }

                BitmapLoader.Save2Jpg(writeableBitmap.Crop(conf.Left, conf.Top, conf.Width, conf.Height), dest);
            }
            return(dest);
        }
示例#5
0
        public static bool Resize(WriteableBitmap bitmap, Stream stream, Size rSize, bool isCenterCrop)
        {
            bool   isResized = false;
            double dr        = JpegHelper.GetMinRatio(bitmap, rSize);

            //if (dr > 1)
            //{
            //가로/세로를 중심점에 맞추어 잘라내기
            if (isCenterCrop)
            {
                //비트맵도 사이즈 변경
                bitmap = bitmap.Resize((int)(bitmap.PixelWidth / dr), (int)(bitmap.PixelHeight / dr), WriteableBitmapExtensions.Interpolation.Bilinear);
                bitmap = bitmap.Crop(new Rect((bitmap.PixelWidth - rSize.Width) / 2, (bitmap.PixelHeight - rSize.Height) / 2, rSize.Width, rSize.Height));
                stream.Seek(0, SeekOrigin.Begin);
                bitmap.SaveJpeg(stream, (int)rSize.Width, (int)rSize.Height, 0, 100);
            }
            else
            {
                //스트림에만 저장
                stream.Seek(0, SeekOrigin.Begin);
                bitmap.SaveJpeg(stream, (int)(bitmap.PixelWidth / dr), (int)(bitmap.PixelHeight / dr), 0, 100);
            }
            isResized = true;
            //}

            return(isResized);
        }
示例#6
0
        public static Layer MergeWith(this Layer thisLayer, Layer otherLayer, string newName, Vector documentsSize)
        {
            thisLayer.GetCloser(otherLayer, out Layer xCloser, out Layer yCloser, out Layer xOther, out Layer yOther);

            // Calculate the offset to the other layer
            int offsetX = Math.Abs(xCloser.OffsetX + xCloser.Width - xOther.OffsetX);
            int offsetY = Math.Abs(yCloser.OffsetY + yCloser.Height - yOther.OffsetY);

            // Calculate the needed width and height of the new layer
            int width  = xCloser.Width + offsetX + xOther.Width;
            int height = yCloser.Height + offsetY + yOther.Height;

            // Merge both layers into a bitmap
            WriteableBitmap mergedBitmap = BitmapUtils.CombineLayers((int)documentsSize.X, (int)documentsSize.Y, new Layer[] { thisLayer, otherLayer });

            mergedBitmap = mergedBitmap.Crop(xCloser.OffsetX, yCloser.OffsetY, width, height);

            // Create the new layer with the merged bitmap
            Layer mergedLayer = new Layer(newName, mergedBitmap)
            {
                Offset = new Thickness(xCloser.OffsetX, yCloser.OffsetY, 0, 0)
            };

            return(mergedLayer);
        }
示例#7
0
        public void CreatePictrue(WriteableBitmap source)
        {
            pictrueshow.Source = source;
            pictrueshow.UpdateLayout();
            int i = 0;

            for (int w = 0; w < GameGlobal.MaxTilesW; w++)
            {
                for (int h = 0; h < GameGlobal.MaxTilesH; h++)
                {
                    var             tile = Tiles.Children[i] as Tile;
                    WriteableBitmap temp = source.Resize((int)Tiles.Width, (int)Tiles.Height, WriteableBitmapExtensions.Interpolation.Bilinear);
                    var             rect = new Rect(w * GameGlobal.TileW, h * GameGlobal.TileH, (int)GameGlobal.TileW, (int)GameGlobal.TileH);
                    temp = temp.Crop(rect);
                    temp.Invalidate();
                    tile.IndexX      = tile.CorrectIndexX = w;
                    tile.IndexY      = tile.CorrectIndexY = h;
                    tile.ImageSource = temp;
                    i += 1;
                }
            }
            foreach (Tile item in Tiles.Children)
            {
                var r    = GameGlobal.Random.Next(Tiles.Children.Count);
                var temp = Tiles.Children[r] as Tile;
                var x    = temp.IndexX;
                var y    = temp.IndexY;
                temp.IndexX = item.IndexX;
                temp.IndexY = item.IndexY;
                item.IndexX = x;
                item.IndexY = y;
            }
            ANI_Starting.Begin();
        }
        public static SpriteDescription TryCreateSprite(int maxElementsCount, List <string> originalUris, List <string> elementCodes, string saveResultUri1, int columnsCount, int widthOfOneItemInPixels, int heightOfOneItemInPixels, int widthInPixels, int heightInPixels, SolidColorBrush backgroundColor1)
        {
            SpriteDescription spriteDescription = new SpriteDescription();

            try
            {
                spriteDescription.WidthInPixels  = widthInPixels;
                spriteDescription.HeightInPixels = heightInPixels;
                spriteDescription.SpritePath     = saveResultUri1;
                spriteDescription.Elements       = new List <SpriteElementData>();
                WriteableBitmap writeableBitmap1 = new WriteableBitmap(widthInPixels, heightInPixels);
                WriteableBitmap writeableBitmap2 = writeableBitmap1;
                Canvas          canvas           = new Canvas();
                SolidColorBrush solidColorBrush  = backgroundColor1;
                ((Panel)canvas).Background = ((Brush)solidColorBrush);
                double num1 = (double)widthInPixels;
                ((FrameworkElement)canvas).Width = num1;
                double num2 = (double)heightInPixels;
                ((FrameworkElement)canvas).Height = num2;
                // ISSUE: variable of the null type

                writeableBitmap2.Render((UIElement)canvas, null);
                writeableBitmap1.Invalidate();
                int num3   = (int)Math.Ceiling((double)maxElementsCount / (double)columnsCount);
                int num4   = widthInPixels / columnsCount;
                int num5   = heightInPixels / num3;
                int num6   = (num4 - widthOfOneItemInPixels) / 2;
                int num7   = (num5 - heightOfOneItemInPixels) / 2;
                int height = 0;
                for (int index = 0; index < originalUris.Count; ++index)
                {
                    int    num8        = index % columnsCount * num4;
                    int    num9        = index / columnsCount * num5;
                    string originalUri = originalUris[index];
                    SpriteCreatorHelper.WriteImageToBitmap(writeableBitmap1, originalUri, num8 + num6, num9 + num7, widthOfOneItemInPixels, heightOfOneItemInPixels);
                    height = num9 + num5;
                    SpriteElementData spriteElementData = new SpriteElementData()
                    {
                        Position = new Rect((double)num8, (double)num9, (double)num4, (double)num5), ElementCode = elementCodes[index]
                    };
                    spriteDescription.Elements.Add(spriteElementData);
                }
                if (height < ((BitmapSource)writeableBitmap1).PixelHeight - 1)
                {
                    writeableBitmap1 = writeableBitmap1.Crop(0, 0, ((BitmapSource)writeableBitmap1).PixelWidth, height);
                    spriteDescription.HeightInPixels = height;
                }
                using (IsolatedStorageFile storeForApplication = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream storageFileStream = storeForApplication.OpenFile(saveResultUri1, FileMode.OpenOrCreate, FileAccess.Write))
                        Extensions.SaveJpeg(writeableBitmap1, (Stream)storageFileStream, spriteDescription.WidthInPixels, spriteDescription.HeightInPixels, 0, 90);
                }
            }
            catch (Exception)
            {
                return(null);
            }
            return(spriteDescription);
        }
        private void CreateCurrentPrint(Rect dirtyModelRect)
        {
            var rect = Rect.Intersect(dirtyModelRect, _modelRect);

            if (rect.IsEmpty)
            {
                return;
            }
            var model = new Rect(_modelRect.Location, _modelRect.Size);

            if (Viewport.HorizontalAxis is Log10Axis)
            {
                var x = Math.Log10(rect.Left);
                rect  = new Rect(x, rect.Top, Math.Log10(rect.Right) - x, rect.Height);
                x     = Math.Log10(model.Left);
                model = new Rect(x, model.Top, Math.Log10(model.Right) - x, model.Height);
            }
            if (Viewport.VerticalAxis is Log10Axis)
            {
                var y = Math.Log10(rect.Top);
                rect  = new Rect(rect.Left, y, rect.Width, Math.Log10(rect.Bottom) - y);
                y     = Math.Log10(model.Top);
                model = new Rect(model.Left, y, model.Width, Math.Log10(model.Bottom) - y);
            }

            var x1 = (int)((rect.Left - model.Left) / model.Width * _bmp.PixelWidth);
            var x2 = (int)((rect.Right - model.Left) / model.Width * _bmp.PixelWidth);
            var y1 = (int)((rect.Top - model.Top) / model.Height * _bmp.PixelHeight);
            var y2 = (int)((rect.Bottom - model.Top) / model.Height * _bmp.PixelHeight);

            if (x1 < 0)
            {
                x1 = 0;
            }
            if (x2 > _bmp.PixelWidth)
            {
                x2 = _bmp.PixelWidth;
            }
            if (x2 <= x1)
            {
                x2 = x1 + 1;
            }
            if (y1 < 0)
            {
                y1 = 0;
            }
            if (y2 > _bmp.PixelHeight)
            {
                y2 = _bmp.PixelHeight;
            }
            if (y2 <= y1)
            {
                y2 = y1 + 1;
            }
            var x0 = Viewport.HorizontalAxis.IsReversed ? _bmp.PixelWidth - x2 : x1;
            var y0 = Viewport.VerticalAxis.IsReversed ? _bmp.PixelHeight - y2 : y1;

            _curBmp = _bmp.Crop(x0, y0, x2 - x1, y2 - y1);
        }
示例#10
0
 private static BitmapSource BitmapSelectionToBmpSource(WriteableBitmap bitmap, Coordinates[] selection, out int offsetX, out int offsetY, out int width, out int height)
 {
     offsetX = selection.Min(min => min.X);
     offsetY = selection.Min(min => min.Y);
     width   = selection.Max(max => max.X) - offsetX + 1;
     height  = selection.Max(max => max.Y) - offsetY + 1;
     return(bitmap.Crop(offsetX, offsetY, width, height));
 }
示例#11
0
        public static BitmapSource BitmapSelectionToBmpSource(WriteableBitmap bitmap, Coordinates[] selection)
        {
            int offsetX = selection.Min(x => x.X);
            int offsetY = selection.Min(x => x.Y);
            int width   = selection.Max(x => x.X) - offsetX + 1;
            int height  = selection.Max(x => x.Y) - offsetY + 1;

            return(bitmap.Crop(offsetX, offsetY, width, height));
        }
示例#12
0
        public static WriteableBitmap CreateImage(EntityModel entityModel)
        {
            WriteableBitmap bankBitmap = BitmapFactory.New(64, 64);

            using (bankBitmap.GetBitmapContext())
            {
                foreach (CharacterTile tile in entityModel.Frame.Tiles)
                {
                    if (string.IsNullOrEmpty(tile.BankID) || string.IsNullOrEmpty(tile.BankTileID))
                    {
                        continue;
                    }

                    BankModel ptModel = ProjectFiles.GetModel <BankModel>(tile.BankID);
                    if (ptModel == null)
                    {
                        continue;
                    }

                    PTTileModel bankModel = ptModel.GetTileModel(tile.BankTileID);

                    if (string.IsNullOrEmpty(bankModel.GUID) && string.IsNullOrEmpty(bankModel.TileSetID))
                    {
                        continue;
                    }

                    WriteableBitmap sourceBitmap = CreateImageUtil.GetCacheBitmap(bankModel.TileSetID);

                    if (sourceBitmap == null)
                    {
                        continue;
                    }

                    using (sourceBitmap.GetBitmapContext())
                    {
                        WriteableBitmap cropped = sourceBitmap.Crop((int)bankModel.Point.X, (int)bankModel.Point.Y, 8, 8);

                        if (tile.FlipX)
                        {
                            cropped = WriteableBitmapExtensions.Flip(cropped, WriteableBitmapExtensions.FlipMode.Vertical);
                        }

                        if (tile.FlipY)
                        {
                            cropped = WriteableBitmapExtensions.Flip(cropped, WriteableBitmapExtensions.FlipMode.Horizontal);
                        }

                        int destX = (int)Math.Floor(tile.Point.X / 8) * 8;
                        int destY = (int)Math.Floor(tile.Point.Y / 8) * 8;

                        Util.CopyBitmapImageToWriteableBitmap(ref bankBitmap, destX, destY, cropped);
                    }
                }
            }

            return(bankBitmap);
        }
示例#13
0
            private WriteableBitmap CropIfNeeded(WriteableBitmap writeableBitmap)
            {
                var height  = writeableBitmap.PixelHeight;
                var width   = writeableBitmap.PixelWidth;
                var xCenter = width / 2;
                var yCenter = height / 2;

                if (width > height)
                {
                    return(writeableBitmap.Crop(xCenter - height / 2, 0, height, height));
                }

                if (width < height)
                {
                    return(writeableBitmap.Crop(0, yCenter - width / 2, width, width));
                }

                return(writeableBitmap);
            }
示例#14
0
        public void LoadChar(WriteableBitmap SourceImage, string charCfg, int LineHeight, int BaseHeigt)
        {
            // Load config
            LoadConfigFromString(charCfg);

            // Load Image fron config
            WriteableBitmap _tmp         = new WriteableBitmap(_xOffset + _xAdvance, LineHeight);
            WriteableBitmap _coreContent = SourceImage.Crop(_x, _y, _width, _height);

            BitmapUtils.PasteBitmap(ref _tmp, _xOffset, _yOffset - BaseHeigt / 2, _coreContent);
            _charImage = _tmp.Clone();
        }
        /// <summary>
        /// Use AForge to automatically detect the image borders, and crop it to size
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AutoFitImage_Click(object sender, RoutedEventArgs e)
        {
            if (_LocalPersistentObject.bitmapProcessingImage == null)
            {
                return;
            }

            WriteableBitmap bmp = _LocalPersistentObject.bitmapProcessingImage as WriteableBitmap;

            bmp = bmp.Resize(1024, 1024, WriteableBitmapExtensions.Interpolation.Bilinear);
            Bitmap image = AForge.Imaging.Image.Clone((Bitmap)bmp, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs = true;
            blobCounter.MinHeight   = 50;
            blobCounter.MinWidth    = 50;

            blobCounter.ProcessImage(image);
            Blob[] blobs = blobCounter.GetObjectsInformation();

            // check for rectangles
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            foreach (var blob in blobs)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blob);
                List <IntPoint> cornerPoints;

                // use the shape checker to extract the corner points
                if (shapeChecker.IsQuadrilateral(edgePoints, out cornerPoints))
                {
                    // only do things if the corners form a rectangle
                    if (shapeChecker.CheckPolygonSubType(cornerPoints) == PolygonSubType.Square)
                    {
                        // here i use the graphics class to draw an overlay, but you
                        // could also just use the cornerPoints list to calculate your
                        // x, y, width, height values.
                        List <AForge.Point> Points = new List <AForge.Point>();

                        bmp = bmp.Crop(cornerPoints[0].X,
                                       cornerPoints[0].Y,
                                       cornerPoints[2].X,
                                       cornerPoints[2].Y);
                    }
                }
            }

            bmp = bmp.Resize(640, 640, WriteableBitmapExtensions.Interpolation.Bilinear);
            _LocalPersistentObject.bitmapProcessingImage = (WriteableBitmap)bmp;

            MainImageFrame.Navigate(typeof(ImageLoadedView), _LocalPersistentObject, new SuppressNavigationTransitionInfo());
        }
示例#16
0
        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            //editBitmap= editBitmap.Crop(0,0,100,100);
            //MainImage.Source = editBitmap;

            ////crop
            //RectangleGeometry rect = new RectangleGeometry();
            //rect.Rect = new Rect((Window.Current.Bounds.Width - 480) / 2, (Window.Current.Bounds.Height - 340) / 2, 480, 340);
            //path.Data = rect;

            if (cropfirstclick)
            {
                cropfirstclick = false;
            }
            else
            {
                var actualwidth = MainImage.ActualWidth;

                var pixelwidth = editBitmap.PixelWidth;


                var ratio  = pixelwidth / actualwidth;
                var margin = (MainGrid.ActualWidth - MainImage.ActualWidth) / 2;

                a.X = (a.X - margin) * ratio;
                a.Y = a.Y * ratio;

                b.X = (b.X - margin) * ratio;
                b.Y = b.Y * ratio;
                var rect1 = new Rect(a, b);

                editBitmap       = editBitmap.Crop(rect1);
                MainImage.Source = editBitmap;

                a = new Point()
                {
                    X = 0,
                    Y = 0
                };

                b     = a;
                rect1 = new Rect(a, b);
                RectangleGeometry rect = new RectangleGeometry();
                rect.Rect      = rect1;
                path.Data      = rect;
                cropfirstclick = true;
            }



            vm.ImgChanged = true;
        }
示例#17
0
        private void CopyPixelsToColorBitmapSmall()
        {
            this.colorBitmapSmall.Lock();

            var colorBitmapCrop = colorBitmap.Crop(0, 0, UserWidth, UserHeight);
            var temprect        = new Int32Rect(0, 0, UserWidth, UserHeight);

            colorBitmapSmall.WritePixels(temprect,
                                         (IntPtr)(colorBitmapCrop.BackBuffer.ToInt64() + temprect.Y * colorBitmapCrop.BackBufferStride + temprect.X * 4),
                                         temprect.Height * colorBitmapCrop.BackBufferStride,
                                         colorBitmapCrop.BackBufferStride);

            this.colorBitmapSmall.Unlock();
        }
        private WriteableBitmap GetCroppedPart(WriteableBitmap source, RectangleF relativeRect)
        {
            double width  = source.Width;
            double height = source.Height;

            double rleft   = relativeRect.Left * width / 100;
            double rtop    = relativeRect.Top * height / 100;
            double rwidth  = relativeRect.Width * width / 100;
            double rheight = relativeRect.Height * height / 100;

            Rect r = new Rect(rleft, rtop, rwidth, rheight);

            return(source.Crop(r));
        }
示例#19
0
        private void DrawPreviewImage(WriteableBitmap bitmap)
        {
            if (live_view_image.ActualWidth == 0 || panel_preview.ActualWidth == 0)
            {
                return;
            }
            double          dw         = panel_preview.ActualWidth / live_view_image.ActualWidth;
            double          dh         = panel_preview.ActualHeight / live_view_image.ActualHeight;
            double          d          = bitmap.PixelWidth * dw / ZoomFactor;
            double          h          = bitmap.PixelHeight * dh / ZoomFactor;
            WriteableBitmap tempbitmap = bitmap.Crop((int)(CentralPoint.X - (d / 2)), (int)(CentralPoint.Y - (h / 2)), (int)d, (int)h);

            tempbitmap.Freeze();
            img_preview.Source = tempbitmap;
        }
示例#20
0
        public static WriteableBitmap Resize(Stream stream, Size rSize, bool isCenterCrop)
        {
            WriteableBitmap bitmap = BitmapFactory.New(0, 0).FromStream(stream);
            double          dr     = JpegHelper.GetMinRatio(bitmap, rSize);

            //if (dr > 1) <= 주석 처리하면 축소 뿐만이 아니라 확대까지 된다.
            //{
            bitmap = bitmap.Resize((int)(bitmap.PixelWidth / dr), (int)(bitmap.PixelHeight / dr), WriteableBitmapExtensions.Interpolation.Bilinear);
            //가로/세로를 중심점에 맞추어 잘라내기
            if (isCenterCrop)
            {
                bitmap = bitmap.Crop(new Rect((bitmap.PixelWidth - rSize.Width) / 2, (bitmap.PixelHeight - rSize.Height) / 2, rSize.Width, rSize.Height));
            }
            //}
            return(bitmap);
        }
示例#21
0
        /// <summary>
        /// Processes the Board image into individual pieces that can be selected and identified seprately.
        /// </summary>
        /// <param name="_bmp"></param>
        private async void ProcessBoard(WriteableBitmap _bmp)
        {
            if (BoardPositions == null)
            {
                return;
            }

            String[] verticalPos = { "a", "b", "c", "d", "e", "f", "g", "h" };

            WriteableBitmap originalBitmap = _bmp;
            int             posSize        = 64;

            UpdateConsole("Processing Board Image into Pieces...");

            originalBitmap = originalBitmap.Resize(512, 512, WriteableBitmapExtensions.Interpolation.Bilinear);

            BoardPositions.Clear();
            for (int v = 7; v >= 0; v--)
            {
                for (int h = 1; h <= 8; h++)
                {
                    int x0 = (h - 1) * posSize;
                    int y0 = (8 - (v + 1)) * posSize;
                    //x1 = h * posSize;
                    //y1 = (8-v) * posSize;

                    PositionInstance bPos = _LocalPersistentObject.queuePositionInstances.Dequeue();
                    bPos.PositionID    = verticalPos[(h - 1)] + (v + 1);
                    bPos.PositionImage = new WriteableBitmap(posSize, posSize);
                    WriteableBitmap modifiedBitmap = originalBitmap.Crop(x0, y0, posSize, posSize);
                    bPos.PositionImage = modifiedBitmap;
                    bPos.PieceID       = (int)PositionInstance.PieceEnum.EPY;

                    modifiedBitmap = modifiedBitmap.Resize(64, 64, WriteableBitmapExtensions.Interpolation.Bilinear);
                    //modifiedBitmap = modifiedBitmap.Gray();
                    bPos.PositionImageByte = await EncodeImage(modifiedBitmap);

                    bPos.PositionImage = modifiedBitmap;
                    bPos.PieceName     = "Empty";
                    BoardPositions.Add(bPos);
                }
            }
            UpdateConsole("Processing Done...");

            //PredictBoardPieces();
        }
示例#22
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var fill = value as CountryAreaFill;

            if (fill != null)
            {
                if (fill.Selected)
                {
                    return(new SolidColorBrush(Color.FromArgb((byte)(fill.MarkerOnly ? 85 : 255), 0, 128, 0)));
                }

                if (!fill.MarkerOnly)
                {
                    if (fill.State == QuestionState.Correct)
                    {
                        if (_cachedImage == null || fill.Flag != _cachedUrl)
                        {
                            LoadImage(fill.Flag);
                        }

                        var scaleX = _cachedImage.PixelWidth / fill.CountryWidth;
                        var scaleY = _cachedImage.PixelHeight / fill.CountryHeight;

                        var x = scaleX < scaleY;

                        double scale = x ? scaleX : scaleY;

                        var scaledWidth  = (int)(fill.Width * scale);
                        var scaledHeight = (int)(fill.Height * scale);

                        var scaledX = (int)(fill.X * scale + (_cachedImage.PixelWidth - fill.CountryWidth * scale) / 2);
                        var scaledY = (int)(fill.Y * scale + (_cachedImage.PixelHeight - fill.CountryHeight * scale) / 2);

                        var brush = new ImageBrush();
                        brush.ImageSource = _cachedImage.Crop(scaledX, scaledY, scaledWidth, scaledHeight);
                        return(brush);
                    }
                    else if (fill.State == QuestionState.Incorrect)
                    {
                        return(new SolidColorBrush(Colors.Gray));
                    }
                }
            }

            return(new SolidColorBrush(fill.MarkerOnly ? Color.FromArgb(85, 0, 0, 0) : Color.FromArgb(255, 31, 31, 31)));
        }
示例#23
0
        public static WriteableBitmap CopyDeep(this WriteableBitmap wbm)
        {
            if (wbm.IsNullOrEmpty())
            {
                return(null);
            }

            if (wbm.Format != PixelFormats.Pbgra32)
            {
                var temp = BitmapFactory.ConvertToPbgra32Format(wbm);
                return(temp.Crop(wbm.ToRect()));
            }
            else
            {
                return(wbm.Crop(wbm.ToRect()));
            }
        }
        private WriteableBitmap FindPlate(IEnumerable <Rect> rects, WriteableBitmap image)
        {
            WriteableBitmap bestCandidate = null;

            foreach (var rect in rects)
            {
                var croppedImage = image.Crop(rect);
                var edgeFilter   = new CannyEdgeDetector();
                var smoothFilter = new Median();
                var grayFilter   = new Grayscale(0.2125, 0.7154, 0.0721);
                var blobCounter  = new BlobCounter();
                var cutTop       = croppedImage.PixelHeight * 0.3;

                croppedImage = croppedImage.Crop(new Rect(0, cutTop, croppedImage.PixelWidth, croppedImage.PixelHeight));

                var bitmap    = (Bitmap)croppedImage;
                var grayImage = grayFilter.Apply(bitmap);

                bitmap = smoothFilter.Apply(grayImage);
                edgeFilter.ApplyInPlace(bitmap);
                blobCounter.ProcessImage(bitmap);

                var blobs         = blobCounter.GetObjectsInformation();
                var possibleChars = new List <Rectangle>();

                foreach (var blob in blobs)
                {
                    var objRectangle = blob.Rectangle;
                    var ratio        = (double)objRectangle.Height / (double)objRectangle.Width;

                    if (ratio >= 1.16d && ratio <= 6.3d)
                    {
                        possibleChars.Add(objRectangle);
                    }
                }

                if (possibleChars.Count == 0)
                {
                    continue;
                }

                bestCandidate = croppedImage;
            }

            return(bestCandidate);
        }
示例#25
0
        //Get the picture and try to decypher it using the database.
        private void CameraPictureReady(object sender, Microsoft.Devices.ContentReadyEventArgs e)
        {
            Stream image = e.ImageStream;

            Dispatcher.BeginInvoke(() =>
            {
                // setting the image in the display and start scanning in the background
                var bmp = new BitmapImage();
                bmp.SetSource(image);
                var tempbmp = new WriteableBitmap(bmp);

                int startX = tempbmp.PixelWidth / 5;
                int startY = tempbmp.PixelHeight / 5;

                var final = tempbmp.Crop(startX, startY, startX * 3, startY * 3);
                scannerWorker.RunWorkerAsync(final);
            });
        }
示例#26
0
        public ImageData GetImage()
        {
            isConnected = true;
            lock (lockSave)
            {
                if (imageChanged && RenderTarget != null)
                {
                    WriteableBitmap wb = new WriteableBitmap(RenderTarget);

                    if (Config != null && app != null && currentSize != null && Config.HideControls)
                    {
                        var x = (int)(double.IsNaN(app.ChatMessageX) ? 0 : app.ChatMessageX);
                        x = x < 0 ? 0 : x;

                        var y = (int)(double.IsNaN(app.ChatBoxY) ? 0 : app.ChatBoxY);
                        //var height = (int)System.Windows.Application.Current.MainWindow.Height - y;
                        var height = (int)app.ChatBoxHeight > 0 ? (int)app.ChatBoxHeight : (int)System.Windows.Application.Current.MainWindow.Height - y;
                        var width  = (int)app.ChatMessageWidth > 0 ? (int)(app.ChatMessageWidth + x - app.ChatBoxX) : (int)app.ChatBoxWidth;

                        currentSize.Width  = width;
                        currentSize.Height = height;
                        wb = wb.Crop(
                            (int)app.ChatBoxX,
                            y,
                            width,
                            height);
                    }
                    else
                    {
                        currentSize.Width  = wb.PixelWidth;
                        currentSize.Height = wb.PixelHeight;
                    }
                    imageData.Size   = currentSize;
                    imageData.Pixels = null;
                    imageData.Pixels = wb.ConvertToByteArray();
                    return(imageData);
                }
                else
                {
                    return(null);
                }
            }
        }
示例#27
0
        public WriteableBitmap Corp(WriteableBitmap bmp)
        {
            if (bmp == null)
            {
                return(null);
            }

            // Filter
            var skin   = _skinColorFilter.Process(bmp);
            var erode  = _erodeFilter.Process(skin);
            var dilate = _dilateFilter.Process(erode);

            dilate = _dilateFilter.Process(dilate);
            dilate = _dilateFilter.Process(dilate);

            // Segment
            var histogram = Histogram.FromWriteabelBitmap(dilate);

            _segmentator.Histogram          = histogram;
            _segmentator.ThresholdLuminance = histogram.Max * 0.1f;
            var foundSegments = _segmentator.Process(dilate);

            // Visualize
            _histogramViz.Histogram = histogram;
            _histogramViz.Visualize(dilate);

            WriteableBitmap result = null;

            foreach (var s in foundSegments)
            {
                // Uses the segment's center and half width, height
                //var c = s.Center;
                //result.DrawEllipseCentered(c.X, c.Y, s.Width >> 1, s.Height >> 1, Colors.Red);


                var x = (s.Center.X - s.Width >> 1) > 0 ? (s.Center.X - s.Width >> 1) : 0;
                var y = (s.Center.Y - s.Height >> 1) > 0 ? (s.Center.Y - s.Height >> 1) : 0;
                result = bmp.Crop(x, y, s.Width, s.Height);
                break;
            }

            return(result);
        }
示例#28
0
        public static void SendSelectedQuadrantSignal(Image image, Point point)
        {
            if (image.ActualWidth == 0 || image.ActualHeight == 0)
            {
                return;
            }

            WriteableBitmap writeableBmp = BitmapFactory.ConvertToPbgra32Format(image.Source as BitmapSource);

            int x = (int)Math.Floor(point.X / 8) * 8;
            int y = (int)Math.Floor(point.Y / 8) * 8;

            WriteableBitmap cropped = writeableBmp.Crop(x, y, 8, 8);

            if (cropped.PixelHeight != 8 || cropped.PixelWidth != 8)
            {
                return;
            }

            SignalManager.Get <OutputSelectedQuadrantSignal>().Dispatch(image, cropped, new Point(x, y));
        }
示例#29
0
 internal void SetUserPhoto(Stream stream, Rect rect)
 {
     this._photoCropRect = rect;
     ImagePreprocessor.PreprocessImage(stream, 1500000, false, (Action <ImagePreprocessResult>)(imPR => Execute.ExecuteOnUIThread((Action)(() =>
     {
         BitmapImage bitmapImage = new BitmapImage();
         Stream stream1 = imPR.Stream;
         bitmapImage.SetSource(stream1);
         WriteableBitmap bmp = new WriteableBitmap((BitmapSource)bitmapImage);
         WriteableBitmap bitmap = bmp.Crop(new Rect()
         {
             Width = (double)bmp.PixelWidth * rect.Width,
             Height = (double)bmp.PixelHeight * rect.Height,
             Y = rect.Top * (double)bmp.PixelHeight,
             X = rect.Left * (double)bmp.PixelWidth
         });
         try
         {
             if (!string.IsNullOrWhiteSpace(this._fullAvatarUri))
             {
                 File.Delete(this._fullAvatarUri);
             }
             using (IsolatedStorageFile storeForApplication = IsolatedStorageFile.GetUserStoreForApplication())
             {
                 MemoryStream memoryStream = new MemoryStream();
                 bitmap.SaveJpeg((Stream)memoryStream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 90);
                 memoryStream.Position = 0L;
                 this._fullAvatarUri = Guid.NewGuid().ToString();
                 ImageCache.Current.TrySetImageForUri("cropped" + this._fullAvatarUri, (Stream)memoryStream);
                 stream.Position = 0L;
                 using (IsolatedStorageFileStream storageFileStream = storeForApplication.OpenFile(this._fullAvatarUri, FileMode.Create, FileAccess.Write))
                     StreamUtils.CopyStream(stream, (Stream)storageFileStream, (Action <double>)null, (Cancellation)null, 0L);
                 this.HavePhoto = true;
             }
         }
         catch
         {
         }
     }))));
 }
示例#30
0
        public static WriteableBitmap AddPadding(WriteableBitmap image)
        {
            int width  = image.PixelWidth;
            int height = image.PixelHeight;
            int size   = 0;
            int n      = 0;

            while (size <= Math.Max(width, height))
            {
                size = (int)Math.Pow(2, n);
                if (size == Math.Max(width, height))
                {
                    break;
                }
                n++;
            }
            var img = image.Crop(0, 0, size, size);

            return(img);

            WriteableBitmap wb = BitmapFactory.New(size, size);
            //for (int i = 0; i < width; i++)
            //{
            //    for (int j = 0; j < height; j++)
            //    {
            //        wb.SetPixel(i, j, image.GetPixel(i, j));
            //    }
            //}
            //for (int i = width; i < size; i++)
            //{
            //    for (int j = height; j < size; j++)
            //    {
            //        wb.SetPixel(i, j, 0);
            //    }
            //}
            //wb.Invalidate();

            //return wb;
        }