从存储在std :: vector中的数据中创建和保存图片



QT中是否有一种方法可以轻松地基于std::vector中存储的数据来创建图片?我的意思是,在矢量中,我使用QPainter绘制的QWidget的每个QPointF点都有颜色,但我不仅需要使用向量中的颜色在QWidget上绘制此图片,还需要保存它作为图片。

如果您知道图像的初始维度并具有带有颜色信息的向量,则可以执行以下操作:

// Image dimensions.
const int width = 2;
const int height = 2;
// Color information: red, green, blue, black pixels
unsigned int colorArray[width * height] =
                    {qRgb(255, 0, 0), qRgb(0, 255, 0), qRgb(0, 0, 255), qRgb(0, 0, 0)};
// Initialize the vector
std::vector<unsigned int> colors(colorArray, colorArray + width * height);
// Create new image with the same dimensions.
QImage img(width, height, QImage::Format_ARGB32);
// Set the pixel colors from the vector.
for (int row = 0; row < height; row++) {
    for (int col = 0; col < width; col++) {
        img.setPixel(row, col, colors[row * width + col]);
    }
}
// Save the resulting image.
img.save("test.png");

最新更新