[英]How to load a sf::Image from an array of pixels in SFML?
I would like to load an image in sfml from a 2d array containing 3 values for each pixel (RGB).我想从包含每个像素 (RGB) 3 个值的 2d 数组加载 sfml 中的图像。 The array would look something like this:该数组将如下所示:
{
{{255, 255, 255}, {255, 255, 255}},
{{255, 255, 255}, {255, 255, 255}}
}
The array above describes a 2x2 image which is white.上面的数组描述了一个 2x2 的白色图像。 How can I turn this into an Image in sfml ( sf::Image
)?如何将其转换为 sfml ( sf::Image
) 中的sf::Image
?
If you want to create an sf::Image
object from a pixel array, then you are interested in the sf::Image::create()
member function overload that takes a const Uint8 *
:如果您想从像素数组创建sf::Image
对象,那么您const Uint8 *
采用const Uint8 *
的sf::Image::create()
成员函数重载const Uint8 *
:
void sf::Image::create(unsigned int width, unsigned int height, const Uint8 * pixels);
As the name suggests, the last parameter, pixels
, corresponds to the array of pixels you want to create the sf::Image
from.顾名思义,最后一个参数pixels
对应于您要从中创建sf::Image
的像素数组。 Note that this pixel array is assumed to be in the RGBA format (this contrasts with the RGB format suggested in the code of the question).请注意,假定此像素阵列采用RGBA格式(这与问题代码中建议的RGB格式形成对比)。 That is, the array must hold four Uint8
s for each pixel – ie, a Uint8
for each component: red , green , blue and alpha .也就是说,数组必须为每个像素保存四个Uint8
即,每个组件一个Uint8
: red 、 green 、 blue和alpha 。
As example, consider the following pixel array, pixels
, made up of six pixels:例如,考虑以下像素阵列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
};
Then, we can create an sf::Image
object from the pixels
array of pixels:然后,我们可以从pixels
数组创建一个sf::Image
对象:
sf::Image image;
image.create(3, 2, pixels);
The pixels of the sf::Image
created above will correspond to these:上面创建的sf::Image
的像素将对应于这些:
This is a 3x2 -pixel image, However, flipping the image's width and height arguments passed to the sf::Image::create()
as done in:这是一个3x2像素的图像,但是,翻转传递给sf::Image::create()
的图像的宽度和高度参数,如下所示:
sf::Image image;
image.create(2, 3, pixels);
This results in a 2x3 -pixel image instead:这会产生一个2x3像素的图像:
Note, however, that both sf::Image
objects above are created from the same array of pixels, pixels
, and they both are made up of six pixels – the pixels are just arranged differently because the images have different dimensions.然而,注意,这两个sf::Image
上述目的是从像素的同一阵列创建的pixels
,并且它们都是由六个像素向上-的像素被布置只是不同,因为这些图像具有不同的尺寸。 Nevertheless, the pixels are the same: a black, a red, a green, a blue, a white and a gray pixel.然而,像素是相同的:黑色、红色、绿色、蓝色、白色和灰色像素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.