我正在尝试创建一个位图图像,并有以下代码:
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uielement);
IBuffer pixels = await renderTargetBitmap.GetPixelsAsync();
. . .
var pixelArray = pixels.ToArray();为了获得ToArray()扩展,我遇到了this问题。所以我补充道:
using System.Runtime.InteropServices.WindowsRuntime; // For ToArray我的密码。但是,当我运行时,会得到以下错误:
引发的异常:“System.ArgumentException”在System.Runtime.WindowsRuntime.dll中 附加信息:指定的缓冲区索引不在缓冲区容量之内。
当我钻研细节时,它在Stack跟踪中写道:
在>System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(IBuffer源代码,UInt32 sourceIndex,Int32计数)
这种提取像素阵列的方法是否仍然适用于UWP?如果是的话,有没有办法从这个错误消息中获得更多的细节?
发布于 2015-12-16 10:50:36
这种提取像素阵列的方法绝对适用于UWP。至于错误,反编译的ToArray()如下所示:
public static byte[] ToArray(this IBuffer source)
{
if (source == null)
throw new ArgumentNullException("source");
return WindowsRuntimeBufferExtensions.ToArray(source, 0U, checked ((int) source.Length));
}换句话说,它调用接受开始索引和长度的ToArray重载:
public static byte[] ToArray(this IBuffer source, uint sourceIndex, int count)
{
if (source == null)
throw new ArgumentNullException("source");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (sourceIndex < 0U)
throw new ArgumentOutOfRangeException("sourceIndex");
if (source.Capacity <= sourceIndex)
throw new ArgumentException(SR.GetString("Argument_BufferIndexExceedsCapacity"));
if ((long) (source.Capacity - sourceIndex) < (long) count)
throw new ArgumentException(SR.GetString("Argument_InsufficientSpaceInSourceBuffer"));
byte[] destination = new byte[count];
WindowsRuntimeBufferExtensions.CopyTo(source, sourceIndex, destination, 0, count);
return destination;
}这句话几乎肯定会引起你的问题:
if (source.Capacity <= sourceIndex)
throw new ArgumentException(SR.GetString("Argument_BufferIndexExceedsCapacity"));...and,因为sourceIndex必然是0,这意味着source.Capacity也是0。
我建议您在代码中添加一些工具来检查IBuffer。
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(element);
IBuffer pixelBuffer = await rtb.GetPixelsAsync();
Debug.WriteLine($"Capacity = {pixelBuffer.Capacity}, Length={pixelBuffer.Length}");
byte[] pixels = pixelBuffer.ToArray();我认为您的问题可能发生在ToArray调用之前。我在自己的UWP应用程序中使用了完全相同的序列,获得了如下所示的调试输出:
Capacity = 216720, Length=216720发布于 2018-12-25 10:01:30
当我试图在UWP应用程序中制作截图时,也遇到了同样的问题。
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uielement);当uielement是Window.Current.Content时,给了我这个例外。
但当我试着
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(null);同样的代码也不例外,给出了UWP应用程序窗口的截图。
https://stackoverflow.com/questions/34196927
复制相似问题