Qvector to Qimage

Asked

Viewed 87 times

4

I have to turn one QVector 2d in a QImage to display the image on a label. The QVector in the case of an array of integers with a value of 0 to 255 representing an image in PGM or PPM, this vector makes gray scale or RGB transformations that are necessary for PDI exercises, but to make it a little easier and make generic methods easier to use I decided to put the image in a Qimage and present the changes.

Doubt is how I can transport QVector<QVector<int> > to the QImage, where you can add the file format information, in case P2 and P3, comment line, number of rows and columns and color scale.

It would be something like this:

P2
# Comentário do arquivo
número de linhas  número de colunas
255
vetor 2d com as informações da imagem.

1 answer

2

You can convert your QVector<QVector<int> > for the PGM format in const char* and let Qt do the rest, because QImage supports PGM.

Example:

In your case just replace the pgm_file for what will be generated by your QVector.

const char* pgm_file =
        "P2\n"
        "# Exemplo\n"
        "24 7\n"
        "15\n"
        "0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0\n"
        "0  3  3  3  3  0  0  7  7  7  7  0  0 11 11 11 11  0  0 15 15 15 15  0\n"
        "0  3  0  0  0  0  0  7  0  0  0  0  0 11  0  0  0  0  0 15  0  0 15  0\n"
        "0  3  3  3  0  0  0  7  7  7  0  0  0 11 11 11  0  0  0 15 15 15 15  0\n"
        "0  3  0  0  0  0  0  7  0  0  0  0  0 11  0  0  0  0  0 15  0  0  0  0\n"
        "0  3  0  0  0  0  0  7  7  7  7  0  0 11 11 11 11  0  0 15  0  0  0  0\n"
        "0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0\n";

QByteArray bytes(pgm_file);

QImage img;
img.loadFromData(bytes, "PGM"); // Pronto. Tá convertido.

// Se quiser ver o resultado.
img.save("resultado.bmp", "BMP");

Converted image: Imagem Convertida

Browser other questions tagged

You are not signed in. Login or sign up in order to post.