Created
September 30, 2019 03:22
-
-
Save JerryNixon/3047f4efad110b6b3d16bb4ce1c19550 to your computer and use it in GitHub Desktop.
Image.Source = await CropImageAsync(Image.Source, new Rectangle(10, 10, 100, 100));
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private async Task<SoftwareBitmapSource> CropImageAsync(ImageSource source, Rectangle rectangle) | |
| { | |
| try | |
| { | |
| SoftwareBitmap bitmap; | |
| var image = source as BitmapImage; | |
| var file = await StorageFile.GetFileFromApplicationUriAsync(image.UriSource); | |
| using (var stream = await file.OpenAsync(FileAccessMode.Read)) | |
| { | |
| var decoder = await BitmapDecoder.CreateAsync(stream); | |
| bitmap = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); | |
| } | |
| using (var memory = new InMemoryRandomAccessStream()) | |
| { | |
| var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, memory); | |
| encoder.SetSoftwareBitmap(bitmap); | |
| encoder.BitmapTransform.Bounds = new BitmapBounds() | |
| { | |
| X = (uint)rectangle.X, | |
| Y = (uint)rectangle.Y, | |
| Height = (uint)rectangle.Height, | |
| Width = (uint)rectangle.Width | |
| }; | |
| await encoder.FlushAsync(); | |
| var decoder = await BitmapDecoder.CreateAsync(memory); | |
| bitmap = await decoder.GetSoftwareBitmapAsync(bitmap.BitmapPixelFormat, bitmap.BitmapAlphaMode); | |
| } | |
| if (bitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || bitmap.BitmapAlphaMode == BitmapAlphaMode.Straight) | |
| { | |
| bitmap = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied); | |
| } | |
| var output = new SoftwareBitmapSource(); | |
| await output.SetBitmapAsync(bitmap); | |
| return output; | |
| } | |
| catch (Exception) | |
| { | |
| throw; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment