65.9K
CodeProject 正在变化。 阅读更多。
Home

Img2Cpp:为嵌入式图像创建 C++ 头文件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.76/5 (8投票s)

2022 年 6 月 29 日

MIT

2分钟阅读

viewsIcon

12392

downloadIcon

317

轻松将图像数据嵌入到您的代码中

img2cpp

引言

如果您为物联网 (IoT) 做了大量编码工作,您可能已经遇到过需要将图像的位图像素数据提供给代码的情况。这些小型设备不能直接使用 JPG 或 PNG 资源并显示它们。

物联网可能不是您需要这种功能的唯一时间。如果您针对没有二进制资源分支的平台,将小工具栏或图标图像嵌入其中也可能很有用。

使用这个烂摊子

首先,有两个可执行文件:img2cppimg2cppw。它们都执行相同的操作,但前者是命令行工具,后者是基于 GUI 的工具。让我们看一下命令行工具的使用说明,这将有助于理解两者

Usage: img2cpp.exe <imagefile> [/name <name>] [/jpg|/16bpp]
  [/gfx14|/gfx17] [/be]
  [/resize [<width>][x<height>]]
  [/arduino] [/out: <headerfile>]

  <imagefile>   The image to convert
  <name>        The base name to use in the header
  <jpg>         Embed as JPG image
  <16bpp>       Convert to 16bpp
  <gfx14/gfx17> Use gfx14 or 17 bindings
  <be>          Use big-endian format
  <resize>      Resize the image. If one dimension
                isn't specified, the aspect ratio
                is preserved.
  <arduino>     Create code for Arduino
  <headerfile>  The output header to generate

imagefile 可以是任何图像。

name 将指示代码中图像的名称。根据生成的代码,引用此名称将获得像素的字节数组(cpp),或像素的实际位图(gfx14/gfx17)。引用 <name>_size 将获得指示位图大小的结构体。

jpg 指示嵌入的数据将是 JPG 流。此选项与 be16bpp 不兼容。

16bpp 表示像素数据应转换为 RGB565 格式。否则,将为 RGB888。

gfx14/gfx17 指示将生成使用 htcw_gfx 图形库的代码,使用 C++14 或 C++17 标准。

be 指示应使用大端输出。通常,对于物联网,情况就是如此,因为大多数显示控制器期望大端格式的像素数据。

resize 指示应调整图像大小。格式为 <width>x<height> 以同时调整宽度和高度,<width> 以调整宽度并保持纵横比,或 x<height> 以对高度执行相同的操作。

arduino 指示应生成 Arduino 框架的代码。数组将在程序闪存 (PROGMEM) 中创建。

headerfile 指示要使用的输出文件。如果命令行未指定此项,则输出将定向到 stdout

编写这个混乱的程序

一旦生成了头文件并将其包含到您的项目中,如何使用它取决于生成的代码类型。以下代码片段假定上面的 namemy_image

标准 C++

// the raw pixel data:
const uint8_t* px0ptr = my_image;
// the size of the bitmap
uint16_t width = my_image_size.width;
uint16_t height = my_image_size.height;

当然,其中不包含任何绘图代码。您需要在代码中渲染或以其他方式使用像素数据。

gfx14/gfx17

// the raw pixel data (not needed):
const uint8_t* px0ptr = my_image_data;
// the size of the bitmap (not needed)
uint16_t width = my_image_size.width;
uint16_t height = my_image_size.height;
// the bitmap (use this)
my_image_t bmp = my_image;

使用 htcw_gfx,您可以像这样将 my_image 绘制到您的 lcd

draw::bitmap(lcd,lcd.bounds(),my_image,my_image.bounds());

免责声明

我还没有测试所有选项的组合。如果您发现对您不起作用的内容,请在评论中留下备注,我会尽快处理。

历史

  • 2022 年 6 月 29 日 - 初始提交
  • 2022 年 6 月 29 日 - 修复了 gfx 下 jpg 生成中的错误
© . All rights reserved.