如何从路径加载 QImage?

How load QImage from path?

我在我的 qt quick 中用相机拍摄了一张图像 application.I 想将路径发送到我的 c++ 代码并在 c++ 中加载该图像 QImage。但是路径是 image://camera/preview_1我不知道如何使用该路径?

Camera {
    id: camera

    imageCapture {
        onImageCaptured: {
            console.log("Preview = "+preview);
            photoPreview.source = preview
            console.log("CapturedImagePath => "+camera.imageCapture.capturedImagePath);
            up.loadImage(preview);
        }
}

c++ class

void UserProfile::loadImage(QString path)
{    
    QUrl imageUrl(path);
    qWarning()<<"imageUrl.host()=>"<<imageUrl.host();
    qWarning()<<"imageUrl.path()=>"<<imageUrl.path();
    qWarning()<<"imageUrl.toLocalFile()=>"<<imageUrl.toLocalFile();
    bool isOpend= m_image.load(path); //m_image is an QImage object
    qWarning()<<"Image loaded=> "<<isOpend;
}

应用输出

D MyApp: qml: Preview = image://camera/preview_1
D MyApp: qml: CapturedImagePath =>
W MyApp: imageUrl.host()=> "camera"
W MyApp: imageUrl.path()=> "/preview_1"
W MyApp: imageUrl.toLocalFile()=> ""
W MyApp: Image loaded=> false

URL image://camera/preview_1 表示图像数据存在于 Camera 创建的 QQuickImageProvider instance. Probably, it's a QQuickImageProvider 实例中。

由于 UserProfile 实例与 camera 实例存在于同一个 QQmlEngine 中,您可以

void UserProfile::loadImage(const QString &path)
{
    auto myQmlEngine = qmlEngine(this);
    if(myQmlEngine==nullptr)
        return;

    QUrl imageUrl(path);
    auto provider = reinterpret_cast<QQuickImageProvider*>( myQmlEngine->imageProvider(imageUrl.host()));

    if (provider->imageType()==QQuickImageProvider::Image){
        QImage img = provider->requestImage(imageUrl.path().remove(0,1),nullptr,QSize());
        // do whatever you want with the image
    } 
}

小心reinterpret_cast。您还必须确保 QQuickImageProvider::imageType() is returning QQmlImageProviderBase::Image.

您也可以使用 capturedImagePath 代替 preview URL 来防止这种复杂性,如果它可以成为您的用例的一个选项。