Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Writing a QRGB.name() to a file, then reading it back out



  • Hello,

    I am attempting to take a QImage, and pass the values of all of its pixels to a file, so that I can read it out again later to reconstruct the same image. I'm feeding the QRGB names to a file with:

        QDataStream out(&qFile);
        qFile.open(QIODevice::WriteOnly);
        for (int i = 0; i < img.height(); ++i) {
            for (int j = 0; j < img.width(); ++j) {
                if(img.valid(i, j)){
                    QString str = img.pixelColor(i,j).name();
                    out << str;
                }
            }
    
        }
        qFile.close();
    

    But I have been unable to retrieve the QRGB.name() values from the file in a way that I can pass them into a QRGB and construct the color. QImage::setPixelColor always comes back with an invalid color reponse. Any tips, help, or suggestions on this would be greatly appreciated, thanks!


  • Lifetime Qt Champion

    Hi
    Are you using
    https://doc.qt.io/qt-5/qcolor.html#setNamedColor
    when you read it in again ?

    Also you could save directly the QColor

    out << img.pixelColor(i,j);



  • @Pollarm said in Writing a QRGB.name() to a file, then reading it back out:

    I am attempting to take a QImage, and pass the values of all of its pixels to a file, so that I can read it out again later to reconstruct the same image. I'm feeding the QRGB names to a file

    Are you doing this because you wish to, for some reason/exercise? Saving the values of every pixel in an image, one at a time, as a string name, is not a usual format for saving in... :)


  • Lifetime Qt Champion

    Hi,

    QImage::save is likely going to be a simpler solution.



  • @JonB The project I'm working keeps multiple images at the same time (drawing one on top of the other), and for the functionality of saving/loading a project in progress I was attempting the angle of encoding the pixels into a file to be read back from later to reconstruct the base image and the one in progress. We decided on encoding for size of the save file reasons. Is there a better way to do this that I didn't think of? Thanks :)


  • Lifetime Qt Champion

    @Pollarm
    Hi
    https://doc.qt.io/qt-5/qdatastream.html
    can be used to directly save QImage to a file.
    So you can construct a "project image" by
    simply streaming the different images to the same file
    and the opposite direction will also be easy.
    Depending on how you have the images stored ( like QVector)
    you can also stream the whole list back and forths directly.



  • @mrjj Thanks! That was so much simpler, and worked like a dream. I think I tried using QDataStream right at the outset of this undertaking, but apparently I was using it incorrectly because I could never get it to construct the image properly!


Log in to reply