簡體   English   中英

如何從路徑加載 QImage?

[英]How load QImage from path?

我在我的 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

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來防止這種復雜性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM