GTKmm:对文件中的图像进行编码

GTKmm : Encode image in the file?

本文关键字:图像 编码 文件 GTKmm      更新时间:2023-10-16

我有一个使用显示图像的UI

add(*manage(new Gtk::Image("image.png")));

但该应用程序在每次lauch时都会从硬盘中提取它,如果它不在那里,它就会坏掉,等等。我如何对image.png进行编码,以便在代码中发送它?

GResource对此非常有用。它允许您在*.gressource.xml文件中列出资源文件(如图像)。glib编译资源实用程序然后从中生成一个.c文件,然后将该.c文件链接到应用程序中。你需要对Makefile.am进行一些更改才能正常实现,但你可以查看一些现有的项目,比如我的Glom项目:

https://git.gnome.org/browse/glom/tree/Makefile_glom.am?id=f79223fa7ebbb0cfc12c6a47366136de478d57cb#n44

然后可以使用API,如Gtk::Image::set_from_resource()。或者,您可以使用API直接获取数据,如g_resources_open_stream(),甚至可以使用g_resources_enumerate_childrem()迭代所有可用的资源。

以下是我的Glom项目中的一些相关承诺:

https://git.gnome.org/browse/glom/commit/?id=f79223fa7ebbb0cfc12c6a47366136de478d57cb

https://git.gnome.org/browse/glom/commit/?id=9cd1b6dab94191abbb9392304e867bddb2bba766

将"image.png"转换为XPM文件;FWIW,标准XPM格式是可编译的C代码。但更重要的是,还有pixbuf和pixmap函数可以直接加载XPM数据。

对于Linux中的gtkmm,您可以将所有资源文件(css、glade、images)转换为一个glib-compile-resources文件。然后将创建一个c文件。因此,无需单独导出资源文件。

为了首先完成所有这些操作,您需要创建*.gresource.xml文件。

我需要将png图像转换为pixbuf格式,由于某些原因png对我不起作用。(你也可以尝试使用png格式)

例如:

<?xml version="1.0" encoding="UTF-8"?>
<gresources>
  <gresource prefix="/myproject">
    <file preprocess="xml-stripblanks" alias="tiltdisplay.glade">Resources/tiltdisplay.glade</file>
    <file alias="styles.css">Resources/styles.css</file>
    <!-- png image is converted to pixbuf image using command >
    < gdk-pixbuf-pixdata -r white_argos.png  white_argos.pixbuf-->
    <file alias="white_argos.pixbuf">Resources/white_argos.pixbuf</file>
  </gresource>
</gresources>

创建此xml文件后,可以使用以下命令生成glib-compile-resources

glib-compile-resources --target=path/to/resources.c --generate-source /path/to/my.gresource.xml

完成此操作后,将此resources.c添加到代码中。为了从c++代码中访问一个项目,请执行以下操作。

img->set_from_resource("/myproject/white_argos.pixbuf"); // gresource prefix + alias
// or
cssProvider->load_from_resource("/myproject/styles.css");
// or
Gtk::Builder::create_from_resource("/myproject/tiltdisplay.glade")