【问题标题】:Creating and saving a picture from data stored in std::vector从存储在 std::vector 中的数据创建和保存图片
【发布时间】:2015-05-05 09:44:56
【问题描述】:

Qt 中有没有一种方法可以轻松地根据存储在std::vector 中的数据创建图片?我的意思是,在矢量中,QWidget 的每个QPointF 点都有颜色,我用QPainter 在其上绘画,但我不仅需要使用颜色在QWidget 上绘制这张图片在矢量中,但也将其保存为图片。

【问题讨论】:

  • 如果将图像的数据存储在矢量中,图像的尺寸是多少?
  • @vahancho 我将颜色值连续存储在向量中,并根据尺寸将它们切片。但如果它更容易,我会创建一个尺寸为宽度*高度的其他数据结构并将数据放入其中。我只是不知道可以使用什么 Qt 方法从中创建和保存图片。

标签: c++ qt vector qpainter qimage


【解决方案1】:

如果您知道图像的初始尺寸并拥有包含颜色信息的矢量,则可以执行以下操作:

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

【讨论】:

  • 谢谢!非常感谢您的帮助!
  • 这感觉有点“慢”,有没有办法正确地使用 vuild 矢量然后直接将其传递给 QImage 或 QPixmap ?
  • @Dariusz,不,您不能直接从向量中创建QImage。但是,您可以从原始数据(uchars 的数组)或 QByteArray 中执行此操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 2020-05-21
相关资源
最近更新 更多