You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NoesisGUI技术问题:XAML中Image元素加载PNG崩溃

解决InvalidCastException: Bitmap转byte[]失败的问题

你遇到的核心问题是EmbeddedTexture的resource属性期望接收byte[]类型数据,但你实际传入了System.Drawing.Bitmap对象,导致运行时触发类型转换异常。咱们一步步来修复这个问题:

1. 先确认嵌入资源的配置

首先得保证你的图片文件已经被正确设置为嵌入资源:

  • 在Visual Studio里选中icon.png和download.jpg
  • 打开属性窗口,把「生成操作」改成嵌入的资源
  • 记住资源的完整命名格式:如果图片在项目根目录,就是[你的项目命名空间].icon.png;如果在子文件夹里,要加上文件夹名,比如[你的项目命名空间].Images.icon.png

2. 修正GetTextureProvider方法的实现

你需要从嵌入资源中读取字节数组,而不是直接传入Bitmap对象。修改后的代码示例如下:

protected override TextureProvider GetTextureProvider()
{
    // 获取当前程序集实例
    var assembly = System.Reflection.Assembly.GetExecutingAssembly();
    
    // 替换成你实际的项目命名空间和资源路径
    string iconResourceFullName = "YourProjectNamespace.icon.png";
    string downloadResourceFullName = "YourProjectNamespace.download.jpg";

    // 封装一个读取资源字节数组的工具方法
    byte[] ExtractResourceBytes(string resourceName)
    {
        using (var resourceStream = assembly.GetManifestResourceStream(resourceName))
        {
            if (resourceStream == null)
                throw new System.IO.FileNotFoundException("未找到指定的嵌入资源", resourceName);
            
            byte[] buffer = new byte[resourceStream.Length];
            resourceStream.Read(buffer, 0, buffer.Length);
            return buffer;
        }
    }

    EmbeddedTexture[] textures = {
        new EmbeddedTexture { filename = "icon.png", resource = ExtractResourceBytes(iconResourceFullName) },
        new EmbeddedTexture { filename = "download.jpg", resource = ExtractResourceBytes(downloadResourceFullName) }
    };

    return new EmbeddedTextureProvider(textures);
}

3. 常见问题排查技巧

  • 如果提示找不到资源,可以用下面的代码输出所有嵌入资源的名称,核对你使用的路径是否正确:
    foreach (var resourceName in assembly.GetManifestResourceNames())
    {
        System.Diagnostics.Debug.WriteLine("嵌入资源名称:" + resourceName);
    }
    
  • 不要直接将Bitmap对象转换后赋值给resource,除非你是从嵌入资源流中创建的Bitmap,否则很容易出现类型不匹配问题
  • 确保EmbeddedTextureProvider的实例化代码完整(你之前的代码没写完),传入的textures数组没有空值

这样修改后,resource属性就能拿到正确的byte[]类型数据,运行时就不会再抛出类型转换异常了。

内容的提问来源于stack exchange,提问作者Sannan Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:23:43