UWP中如何从CapturedPhoto获取子图像并保存摄像头拍摄图片区域
Capture and Crop a Specific Region from Camera Photo (Windows.Media.Capture)
Great progress so far! To save just a specific region of your captured photo, we’ll extend your existing code to crop the image right after capture before saving it. Here’s a complete, working implementation with clear steps:
Core Workflow:
- Wrap up the low-lag capture setup
- Extract the captured frame as a
SoftwareBitmap - Define your target crop area (adjust coordinates/size to your needs)
- Create a cropped version of the bitmap
- Encode and save the cropped image to a file
Full Updated Code:
using Windows.Media.Capture; using Windows.Media.MediaProperties; using Windows.Storage; using Windows.UI.Xaml.Media.Imaging; private MediaCapture _mediaCapture; private bool _isPreviewing = false; // Initialize camera and start preview public async Task InitializeCameraAsync() { _mediaCapture = new MediaCapture(); await _mediaCapture.InitializeAsync(); await _mediaCapture.StartPreviewAsync(); _isPreviewing = true; } // Capture photo, crop desired region, and save public async void TakePhoto() { if (_mediaCapture == null || !_isPreviewing) return; try { // Prepare low-lag photo capture with uncompressed BGRA8 format var lowLagCapture = await _mediaCapture.PrepareLowLagPhotoCaptureAsync( ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8)); // Capture the photo frame var capturedPhoto = await lowLagCapture.CaptureAsync(); // Extract the original bitmap from the captured frame using (var originalBitmap = capturedPhoto.Frame.SoftwareBitmap) { // Define your crop region (example: 200x200 square starting at (100, 100)) // Note: Coordinates are relative to the original bitmap's width/height var cropBounds = new Windows.Foundation.Rect(100, 100, 200, 200); // Create the cropped bitmap using (var croppedBitmap = SoftwareBitmap.Crop(originalBitmap, cropBounds)) { // Convert to BGRA8 with ignored alpha (required for most encoders) if (croppedBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || croppedBitmap.BitmapAlphaMode != BitmapAlphaMode.Ignore) { croppedBitmap = SoftwareBitmap.Convert(croppedBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore); } // Save the cropped image to your Pictures library await SaveCroppedImage(croppedBitmap); } } // Clean up capture resources await lowLagCapture.FinishAsync(); } catch (Exception ex) { // Handle common errors (e.g., invalid crop bounds, camera access issues) System.Diagnostics.Debug.WriteLine($"Error: {ex.Message}"); } } // Helper method to save the cropped bitmap to a file private async Task SaveCroppedImage(SoftwareBitmap bitmap) { // Create a unique file name in the Pictures library var saveFile = await KnownFolders.PicturesLibrary.CreateFileAsync( $"CroppedShot_{DateTime.Now:yyyyMMddHHmmss}.png", CreationCollisionOption.GenerateUniqueName); // Encode and write the bitmap to the file using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetSoftwareBitmap(bitmap); await encoder.FlushAsync(); } }
Key Tips:
- Adjust the Crop Region: Modify the
cropBoundsvalues to match your desired area. Make sure the rectangle stays within the original bitmap’s dimensions to avoid runtime errors. - Resource Cleanup: The
usingstatements ensure bitmaps and streams are properly disposed, preventing memory leaks. - Change File Format: To save as JPEG instead of PNG, replace
BitmapEncoder.PngEncoderIdwithBitmapEncoder.JpegEncoderIdand update the file extension to.jpg. - Permissions: Ensure your app has the
webcamandpicturesLibrarycapabilities enabled in your Package.appxmanifest file.
内容的提问来源于stack exchange,提问作者Erik Bong
相关产品推荐
相关产品推荐

