【问题标题】:How load QImage from path?如何从路径加载 QImage?
【发布时间】:2023-03-14 09:36:01
【问题描述】:

我在我的 qt 快速应用程序中用相机捕获了一个图像。我想将路径发送到我的 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++ 类

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

【问题讨论】:

标签: c++ qt qml qimage


【解决方案1】:

URL image://camera/preview_1 表示图像数据存在于QQuickImageProvider 实例中。可能是由Camera 创建的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() 正在返回 QQmlImageProviderBase::Image

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

【讨论】:

  • 您的答案有效,但在将 imageUrl.host().remove(0,1) 更改为 imageUrl.path().remove(0,1) 之后
猜你喜欢
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-01
  • 2020-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多