I need to fetch a jpeg image from a REST API call. I use XMLHttpRequest as the request requires authentication headers (i.e. I can't just create an Image and set the source to the URL with user:passwd@url).
I thought I'd be able to use a Canvas and call drawImage by setting the REST data to a CanvasImageData object. However, it doesn't draw anything, nor does it produce an error. The REST call returns Content-Type: image/jpeg and the Transfer-Encoding: chunked.
Should this approach work, or am I missing something else? Any better suggestions?
// map_request.imageBytes is a property that holds the binary response from the REST query
Canvas {
id: location_map
width: 2400
height: 1500
contextType: '2d'
onPaint: {
if (context && map_request.imageBytes)
{
var cid = context.createImageData(width, height);
cid.data = map_request.imageBytes;
context.drawImage(cid, 0, 0);
}
}
The proper solution is to create a QQuickImageProvider as @folibis instructed. However, since I am using Qt5.5, I can't make a QQuickAsyncImageProvider (which is introduced in Qt5.6). Instead, you have to set the Flags when constructing the QQuickImageProvider to QQmlImageProviderBase::ForceAsynchronousImageLoading. This flag ensures that calling requestImage doesn't block the main GUI thread.
However, requestImage expects the Image to be returned, causing a challenge to fetch the Image data from the network without blocking that thread. QNetworkAccessManager returns its status with signals, and QQuickImageProvider isn't a QObject, so I made a helper class to monitor the signals for the QNetworkReply.
and
Then in
requestImage()
I checkfinished
and callbefore I create the Image to return with
I omitted the details of creating a QNetworkRequest, as that is well-documented.