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

Calculating image ratio



  • Hi,

    I would like to calculate the aspect ratio of an image and display the result. I do not actually want to modify the image, I just want to know the ratio. All I tried resulted in a ratio of 1. Why is that so?

        QImage image(imageFileName);
        double ratio = image.width()/image.height();
        qDebug() << image.width() << image.hieght() << "ratio" << ratio;
    

    The output is: 3264 2592 ratio 1


  • Qt Champions 2017

    Dividing an integer to an integer gives you an integer. Cast one of the integers to a floating point type before hand (also I advise reading a bit on implicit casts in C++).

    double ratio = static_cast<double>(image.width()) / image.height();
    


  • Sorry for the dumb question I am new to Qt and coming from PHP.

    Playing around I saw that Qt or QImage does not know the correct orientation of an image. So width is not always the width. I guess this is only a problem on OS X because it stores the rotation info differently. But I did not see an option get the orientation. I read that you need an extra library for that. Was there anything build in Qt recently so that I can do that from Qt?


  • Qt Champions 2017

    @Sikarjan said in Calculating image ratio:

    Sorry for the dumb question I am new to Qt and coming from PHP.

    I didn't mean the question is dumb, I meant that Qt's just a library, not a language itself. You need to know (more or less) C++ to be able to use it, that's why I referred you to the C++'s language reference.

    @Sikarjan said in Calculating image ratio:

    So width is not always the width. I guess this is only a problem on OS X because it stores the rotation info differently. But I did not see an option get the orientation. I read that you need an extra library for that. Was there anything build in Qt recently so that I can do that from Qt?

    Do you mean the image's metadata? QImage should be aware of it and correctly load it, so width(), should be width.



  • I played around with the image scale example, which loads multiple images and puts them in a grid with 100 x 100 thumbnails. Here some images were rotated by 90°. I read in an older post that QImage cannot read the EXIF data of the image and therefore is not aware of the orientation.


  • Qt Champions 2017

    @Sikarjan said in Calculating image ratio:

    I read in an older post that QImage cannot read the EXIF data of the image and therefore is not aware of the orientation.

    Maybe, I don't know. If that's true and you need to read the EXIF header, then I think you indeed need an external library.


Log in to reply