c++gtkgtk3gtkmmgtkmm3

Error while opening png image with Gdk::Pixbuf::create_from_resource


I'm trying to read the png image with Gdk::Pixbuf::create_from_resource:

#include <iostream>
#include <gtkmm.h>

int main(int argc, char *argv[])
{
    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("image.png");
    } catch (const Glib::Error &error) {
        std::cerr << "Failed to load an image: " << error.what() << std::endl;
    }

    return app->run(window);
}

But an error occurs:

 $ ./a.out 
Failed to load an image: The resource at “image.png” does not exist
 $ ls -l
total 128
-rwxrwxr-x. 1 user user 36528 Jul 18 15:01 a.out
-rw-r--r--. 1 user user 88792 Jul 18 15:00 image.png
-rw-r--r--. 1 user user   449 Jul 18 15:00 main.cpp

gtkmm version 3.24.6


Solution

  • If you want to load an image file directly into your program, instead of:

    Glib::RefPtr<Gdk::Pixbuf> image
            = Gdk::Pixbuf::create_from_resource("image.png");
    

    you would use the following statement:

    Glib::RefPtr<Gdk::Pixbuf> image
            = Gdk::Pixbuf::create_from_file("image.png");
    

    If you do want to use the image file as a resource, you would need to first generate a resource file with the "glib-compile-resources" function using a resource definition XML file. For example.

    glib-compile-resources --target=image.c --generate-source resource.xml
    

    In your XML file, you probably would have some type of definition such as the following.

    <gresources>
        <gresource prefix="Image">
            <file preprocess="xml-stripblanks">image.png</file>
        </gresource>
    </gresources>
    

    Then in your program, your creation statement would be similar to the following.

    Glib::RefPtr<Gdk::Pixbuf> image = Gdk::Pixbuf::create_from_resource("Image/image.png");
    

    Finally, you would revise your compile command to include the generated resource file with your "main.cpp" file to create your program.

    g++ -Wno-format -o a.out main.cpp image.c `pkg-config --cflags --libs gtkmm-3.0` `pkg-config --cflags --libs gdkmm-3.0`
    

    Hope that clarifies things.

    Regards.