Good day. I need to crop the image in the selected area as follows:
double scale = 1; if (double.IsNaN(scale) || double.IsInfinity(scale)) { scale = 1; } double sourceImageWidthScale = Container.ActualWidth / WB_CapturedImage.PixelWidth; double sourceImageHeightScale = Container.ActualHeight / WB_CapturedImage.PixelHeight; Size previewImageSize = new Size( rect.Width / sourceImageWidthScale, rect.Height / sourceImageHeightScale); double previewImageScale = 1; if (previewImageSize.Width <= Container.ActualWidth && previewImageSize.Height <= Container.ActualHeight) { previewImageScale = Math.Max(Container.ActualWidth / previewImageSize.Width, Container.ActualHeight / previewImageSize.Height); } // Convert start point and size to integer. uint startPointX = (uint)Math.Floor(Point3.Position.X / sourceImageWidthScale * previewImageScale); uint startPointY = (uint)Math.Floor(Point3.Position.Y / sourceImageWidthScale * previewImageScale); uint height = (uint)Math.Floor(previewImageSize.Height * previewImageScale); uint width = (uint)Math.Floor(previewImageSize.Width * previewImageScale); using (IRandomAccessStream stream = await storgae.OpenReadAsync()) { // Create a decoder from the stream. With the decoder, we can get // the properties of the image. BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); // The scaledSize of original image. uint scaledWidth = (uint)Math.Floor(decoder.PixelWidth * previewImageScale); uint scaledHeight = (uint)Math.Floor(decoder.PixelHeight * previewImageScale); // Refine the start point and the size. if (startPointX + width > scaledWidth) { startPointX = scaledWidth - width; } if (startPointY + height > scaledHeight) { startPointY = scaledHeight - height; } // Create cropping BitmapTransform and define the bounds. BitmapTransform transform = new BitmapTransform(); BitmapBounds bounds = new BitmapBounds(); bounds.X = startPointX; bounds.Y = startPointY; bounds.Height = height; bounds.Width = width; transform.Bounds = bounds; transform.ScaledWidth = scaledWidth; transform.ScaledHeight = scaledHeight; // Get the cropped pixels within the bounds of transform. PixelDataProvider pix = await decoder.GetPixelDataAsync( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb); byte[] pixels = pix.DetachPixelData(); // Stream the bytes into a WriteableBitmap WriteableBitmap cropBmp = new WriteableBitmap((int)width, (int)height); Stream pixStream = cropBmp.PixelBuffer.AsStream(); pixStream.Write(pixels, 0, (int)(width * height * 4)); Target.Source = cropBmp; rect.Visibility = Visibility.Collapsed; } Where
StorageFile storgae; WriteableBitmap WB_CapturedImage; Canvas Container = new Canvas(); I correctly cut off square pictures (300x300, 600x600 ..). Rectangular image cut the offset area. Tell me you did something wrong?