我想拍照,将其调整为1000x1000并将其保存到图片库。问题是图片左右两侧都有一个黑色边框,不透明。就像相机在我的预览区域外拍摄了一些像素。我也试图让CaptureElement像一个正方形,但MediaCapture流无法按预期填充该区域......
<Grid Style="{StaticResource LayoutGridStyle}">
<CaptureElement Name="CameraPreview" VerticalAlignment="Top" HorizontalAlignment="Left" />
<Button Content="Take photo" Click="TakePhoto_Click" HorizontalAlignment="Center" Margin="0,0,0,100" VerticalAlignment="Bottom" FontSize="30"/>
</Grid>
背后的相机页面代码
private async Task InitPreviewCaptureAsync()
{
CameraPreview.Width = Window.Current.Bounds.Width;
CameraPreview.Height = Window.Current.Bounds.Height;
CameraPreview.Source = MediaCapture;
CameraPreview.Stretch = Windows.UI.Xaml.Media.Stretch.UniformToFill;
MediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
await MediaCapture.StartPreviewAsync();
Root.IsPreviewing = true;
Root.PreviewElement = CameraPreview;
}
private async Task<string> TakePhotoAsync()
{
string filename = string.Format("myphotoapp_{0}.jpg", DateTime.Now.ToString("yyMMddHHmms"));
var imageFile = await KnownFolders.CameraRoll.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);
await MediaCapture.CapturePhotoToStorageFileAsync(Windows.Media.MediaProperties.ImageEncodingProperties.CreateJpeg(), imageFile);
await Root.CleanupCaptureResourcesAsync();
filename = imageFile.Name;
imageFile = null;
return filename;
}
最后是从我的上传页面调整大小的代码
private async Task LoadImageAsync()
{
var imageFile = await KnownFolders.CameraRoll.GetFileAsync(StorageFileName);
using (var sourceStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
ImageStream = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(ImageStream, decoder);
encoder.BitmapTransform.ScaledWidth = 1000 * decoder.PixelWidth / decoder.PixelHeight;
encoder.BitmapTransform.ScaledHeight = 1000;
encoder.BitmapTransform.Bounds = new BitmapBounds { Height = 1000, Width = 1000, X = 0, Y = 0 };
encoder.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees;
await encoder.FlushAsync();
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(ImageStream);
UploadedImage.Source = bitmapImage;
if (!ImageHasBeenResized)
{
using (var outputStream = sourceStream.GetOutputStreamAt(0))
{
using (var inputStream = ImageStream.GetInputStreamAt(0))
{
IBuffer storageFileBuffer = new byte[ImageStream.Size].AsBuffer();
await inputStream.ReadAsync(storageFileBuffer, storageFileBuffer.Length, InputStreamOptions.None);
await outputStream.WriteAsync(storageFileBuffer);
}
}
}
}
}