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

使用Gdk::Pixbuf::create_from_resource加载PNG图片报错:资源不存在

问题原因

Gdk::Pixbuf::create_from_resource并不是用来读取本地文件系统里的普通图片的——它的作用是读取嵌入到程序二进制中的GResource打包资源。你的图片在当前目录,但没被打包成GResource,所以函数找不到它。

解决方案

有两种方式解决这个问题,按需选择:

方案一:直接加载本地文件(最简单)

把create_from_resource替换成create_from_file,直接读取当前目录的图片文件:

修改后的代码片段:

try  {
    Glib::RefPtr<Gdk::Pixbuf> image
        = Gdk::Pixbuf::create_from_file("image.png");
} catch (const Glib::Error &error) {
    std::cerr << "Failed to load an image: " << error.what() << std::endl;
}

这样修改后,编译运行就能正常加载当前目录的image.png了。

方案二:打包图片为GResource(适合需要嵌入资源的场景)

如果需要把图片嵌入到程序里,避免单独携带文件,可以按以下步骤操作:

  1. 创建资源定义文件resources.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<gresources>
  <gresource prefix="/org/gtkmm/examples/base">
    <file>image.png</file>
  </gresource>
</gresources>

这里的prefix要和你程序的application ID(org.gtkmm.examples.base)对应,方便管理资源路径。

  1. 用glib-compile-resources工具生成C代码:
glib-compile-resources --generate-source --target=resources.c resources.xml

执行后会生成resources.c文件,里面包含了图片的二进制数据,同时会生成对应的头文件resources.h。

  1. 修改代码,注册资源并加载:
    在main函数开头添加资源注册的代码,然后用完整的资源路径加载图片:
#include <iostream>
#include <gtkmm.h>
#include "resources.h"

int main(int argc, char *argv[])
{
    // 注册资源
    Glib::RefPtr<Glib::Resource> resource = Glib::Resource::create_from_file("resources.xml");
    Glib::Resources::register_resource(resource);

    auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");

    Gtk::Window window;
    window.set_default_size(100, 100);

    try  {
        // 使用完整的资源路径,前缀+文件名
        Glib::RefPtr<Gdk::Pixbuf> image
            = Gdk::Pixbuf::create_from_resource("/org/gtkmm/examples/base/image.png");
    } catch (const Glib::Error &error) {
        std::cerr << "Failed to load an image: " << error.what() << std::endl;
    }

    return app->run(window);
}
  1. 编译时要把生成的resources.c一起编译:
g++ main.cpp resources.c `pkg-config --cflags --libs gtkmm-3.0` -o a.out

这样编译出来的程序就包含了图片资源,运行时不需要单独携带image.png了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 02:06:23