[SOLVED] Problem with QPixmap scaled



  • Hello!
    I'm trying to resize an image with QPixmap.
    This is the code:

    void ImageResize::resize(QString inputImage, QString dir, int width, int height)
    {
        QFileInfo f(inputImage);
        QPixmap pixmap(f.filePath());
        pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        QFile file(dir + f.fileName());
        file.open(QIODevice::WriteOnly);
        pixmap.save(&file, "jpg", 100);
        file.close();
    }
    

    The problem is that the images are copied to the new destination without being resized.
    Where am I wrong?


  • Qt Champions 2016

    @fermatqt said:
    pixmap.scaled returns the scaled bitmap and do not modify the given one, as far as I can remember :)

    so try with
    pixmap = pixmap.scaled(...)



  • @mrjj I tried as you said, but in this case the images are corrupted (zero bytes).

    void ImageResize::resize(QString inputImage, QString dir, int width, int height)
    {
        QFileInfo f(inputImage);
        QPixmap pixmap(f.filePath());
        pixmap = pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        QFile file(dir + f.fileName());
        file.open(QIODevice::WriteOnly);
        pixmap.save(&file, "jpg", 100);
        file.close();
    }
    


  • The problem occurs because put width or height to zero.
    So I did the following:

    void ImageResize::resize(QString inputImage, QString dir, int width, int height)
    {
        QFileInfo f(inputImage);
        QPixmap pixmap(inputImage);
        QPixmap newPixmap;
        if(width == 0)
        {
            newPixmap = pixmap.scaledToHeight(height, Qt::SmoothTransformation);
        }
        else if(height == 0)
        {
            newPixmap = pixmap.scaledToWidth(width, Qt::SmoothTransformation);
        }
        else
        {
            newPixmap = pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        }
        QFile file(dir + f.fileName());
        file.open(QIODevice::WriteOnly);
        newPixmap.save(&file, "JPG", 100);
        file.close();
    }
    

    It seems to work.


  • Qt Champions 2016

    ah ok.
    Good to know that it will (try) to scale an image to 0,0 :)

    Remember to flag as solved if your happy.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.