【问题标题】:How to load a sf::Image from an array of pixels in SFML?如何从 SFML 中的像素数组加载 sf::Image?
【发布时间】:2020-09-17 23:29:43
【问题描述】:

我想从包含每个像素 (RGB) 的 3 个值的二维数组中加载 sfml 中的图像。数组看起来像这样:

{
 {{255, 255, 255}, {255, 255, 255}},
 {{255, 255, 255}, {255, 255, 255}}
}

上面的数组描述了一个 2x2 的白色图像。如何将其转换为 sfml (sf::Image) 中的图像?

【问题讨论】:

标签: c++ sfml


【解决方案1】:

如果您想从像素数组创建sf::Image 对象,那么您对采用const Uint8 *sf::Image::create() 成员函数重载感兴趣:

void sf::Image::create(unsigned int width, unsigned int height, const Uint8 * pixels);  

顾名思义,最后一个参数pixels 对应于您要从中创建sf::Image 的像素数组。请注意,此像素阵列假定为 RGBA format(这与问题代码中建议的 RGB 格式形成对比)。也就是说,数组必须为 每个像素 保存 四个 Uint8s - 即,每个组件都有一个 Uint8red,green、bluealpha


例如,考虑以下像素数组pixels,由六个像素组成:

const unsigned numPixels = 6;
sf::Uint8 pixels[4 * numPixels] = {
    0,   0,   0,   255, // black
    255, 0,   0,   255, // red
    0,   255, 0,   255, // green
    0,   0,   255, 255, // blue
    255, 255, 255, 255, // white
    128, 128, 128, 255, // gray
};

然后,我们可以从pixels 像素数组创建一个sf::Image 对象:

sf::Image image;
image.create(3, 2, pixels);

上面创建的sf::Image 的像素将对应这些:

这是一个 3x2 像素的图像,但是,翻转图像的 widthheight 参数传递给sf::Image::create()

sf::Image image;
image.create(2, 3, pixels);

这会产生 2x3 像素的图像:

但是请注意,上面的两个 sf::Image 对象都是从相同的像素数组 pixels 创建的,并且它们都由 六个 像素组成 - 像素只是排列方式不同因为图像有不同的尺寸。然而,像素是相同的:黑色、红色、绿色、蓝色、白色和灰色像素。

【讨论】:

    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2011-10-30
    • 2012-11-29
    相关资源
    最近更新 更多