Search code examples
c++qtvectorqpainterqimage

Creating and saving a picture from data stored in std::vector


Is there a method in Qt with which one can easily create a picture based on data stored in a std::vector? I mean that in the vector there are colors for each QPointF points of a QWidget on which I'm painting with QPainter, but I don't only need to draw this picture on the QWidget using the colors in the vector, but to save it as a picture too.


Solution

  • If you know the initial dimensions of your image and have a vector with the color information, you can do the following:

    // 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");