Qt根据QLabel的大小调整图片的大小

		using namespace cv;
        Mat LoadImage=imread(filename.toLocal8Bit().toStdString());
        if(LoadImage.empty()){
            QMessageBox::critical(nullptr, "Cant load the image", "Can't load the image!");
            ui->InputLineEdit->clear();
        }
        else{
            QImage ShowLoadImage=cvMat2QImage(LoadImage);
            float ImageRatio=static_cast<float>(ShowLoadImage.width())/static_cast<float>(ShowLoadImage.height());
            float LabelRatio=static_cast<float>(ui->ShowImageLabel1->width())/static_cast<float>(ui->ShowImageLabel1->height());
            float ImageScaleRatio;
            if(ImageRatio>LabelRatio){
                ImageScaleRatio=static_cast<float>(ui->ShowImageLabel1->width())/static_cast<float>(ShowLoadImage.width());
                ShowLoadImage=ShowLoadImage.scaled(ui->ShowImageLabel1->width(), static_cast<int>(ShowLoadImage.height()*ImageScaleRatio));
            }
            else{
                ImageScaleRatio=static_cast<float>(ui->ShowImageLabel1->height())/static_cast<float>(ShowLoadImage.height());
                ShowLoadImage=ShowLoadImage.scaled(static_cast<int>(ShowLoadImage.width()*ImageScaleRatio), ui->ShowImageLabel1->height());
            }
            ui->ShowImageLabel1->setPixmap(QPixmap::fromImage(ShowLoadImage));
        }

上述方法较为麻烦,且像素不清,可以采用下面的方法,

ui->ShowImageLabel1->setPixmap(QPixmap::fromImage(ShowLoadImage).scaled(ui->ShowImageLabel1->width(),
                                                                        ui->ShowImageLabel1->height(),
                                                                        Qt::KeepAspectRatio,
                                                                        Qt::SmoothTransformation));

你可能感兴趣的:(Qt,OpenCV)