问题
I'm making a universal app. In my app I need to use RenderTargetBitmap to convert an Image and a TextBlock over the image into a JPEG photo. On the Windows 8.1 project, everything works as expected, but not on the Windows Phone 8.1 one. Could you help me with that? Thank you.
My code is as follows:
async Task SaveVisualElementToFile(FrameworkElement element, StorageFile file, int imageWidth, int imageHeight)
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(element, imageWidth, imageHeight);
var pixels = await renderTargetBitmap.GetPixelsAsync();
using(IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await
BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
byte[] bytes = pixels.ToArray();
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)imageWidth, (uint)imageHeight,
96, 96, bytes);
await encoder.FlushAsync();
}
}
It is throwing the error in the line byte[] bytes = pixels.ToArray(); The error is: "The specified buffer index is not within the buffer capacity"
I am calling the method with this:
var file = await KnownFolders.CameraRoll.CreateFileAsync("abc.jpg", CreationCollisionOption.ReplaceExisting);
Image image = new Image();
image.Source = bitmapImage;
image.VerticalAlignment = VerticalAlignment.Top;
TextBlock tb = new TextBlock();
tb.FontSize = bitmapImage.PixelHeight / 15;
tb.Foreground = new SolidColorBrush(Colors.Yellow);
tb.Text = "abcdefg";
tb.VerticalAlignment = VerticalAlignment.Bottom;
tb.HorizontalAlignment = HorizontalAlignment.Center;
Grid grid = new Grid();
grid.Children.Add(image);
grid.Children.Add(tb);
renderBmpGrid.Children.Add(grid); //renderBmpGrid is a Grid of
//the visual tree
await SaveVisualElementToFile(grid, file, bitmapImage.PixelWidth, bitmapImage.PixelHeight);
来源:https://stackoverflow.com/questions/28501503/rendertargetbitmap-works-fine-on-windows-8-1-but-not-on-windows-phone-8-1