加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在UWP中使用RenderTargetBitmap时出错

发布时间:2020-12-15 22:23:52 所属栏目:百科 来源:网络整理
导读:我正在尝试创建位图图像,并具有以下代码: RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();await renderTargetBitmap.RenderAsync(uielement);IBuffer pixels = await renderTargetBitmap.GetPixelsAsync();. . .var pixelArray = pixel
我正在尝试创建位图图像,并具有以下代码:

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

给我的代码.但是,当我运行时,我收到以下错误:

Exception thrown: ‘System.ArgumentException’ in
System.Runtime.WindowsRuntime.dll

Additional information: The specified buffer index is not within the
buffer capacity.

当我深入研究细节时,它在Stack Trace中说:

at >System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(IBuffer source,UInt32 sourceIndex,Int32 count)
at >System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(IBuffer source)

这种提取像素阵列的方法是否仍适用于UWP?如果是,是否有任何方法可以从此错误消息中获取更多详细信息?

解决方法

提取像素阵列的方法肯定适用于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,count);
  return destination;
}

这些线几乎肯定会导致你的问题:

if (source.Capacity <= sourceIndex)
    throw new ArgumentException(SR.GetString("Argument_BufferIndexExceedsCapacity"));

…并且由于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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读