user2339449
user2339449

Reputation: 63

How do I import an ImageMagick image into a Qt5 app without ImageMagick?

I'm using libdmtx in a Qt5 application. (I've played around with some alternatives and I won't go into why they were not right for me...)

I would like to display a datamatrix barcode at one point in my UI. I have a line like this which should work if I link against ImageMagick:

MagickConstituteImage(wand, enc->image->width, enc->image->height,
     "RGB", CharPixel, enc->image->pxl);

The thing is, I'm already using Qt5 and I don't really want to add a whole extra library to display one image. There is some explanation of what this line does on the ImageMagick website.

I really want to load it into a valid QImage (although pixmaps and such are fine too, the point is I want to display it). I've tried all the relevant functions on this page and am running out of ideas: https://doc.qt.io/qt-5/qimage.html#QImage-3

The members of enc->image are named approximately thus:

            bitsperchannel
        bitsperpixel
        bytesperpixel
        channelcount
        channelstart
        height
        imageFlip
        pixelPacking
        pxl
        rowPadBytes
        rowSizeBytes
        width

Thanks in advance!

Upvotes: 0

Views: 361

Answers (1)

user2339449
user2339449

Reputation: 63

OK, this wasn't meant to be one of those answer-my-own-question things. What I really thought would happen would be that I would link against ImageMagick anyway, and maybe someone would post an answer that helped the next guy down the line.

But, I got it myself.

QImage image(enc->image->pxl, enc->image->width, enc->image->height, QImage::Format_RGB888);

What are those params? Magic? No. Here's the signature for the constructor:

QImage::QImage(const uchar *data, int width, int height, Format format, QImageCleanupFunction cleanupFunction = Q_NULLPTR, void *cleanupInfo = Q_NULLPTR)

I got that from here: https://doc.qt.io/qt-5/qimage.html#QImage-4

The first param, obviously pxl is an unsigned char *. So that narrowed down my choices a bit. width and height are pretty obvious I think. The trick was selecting the right encoding format. I know it's RGB because in the ImageMagick code it's specified as RGB. So that narrows that down a bit. But it wasn't enough. I know that the pixel thingies come in triplets because the ImageMagick line specifies them, RGB, in triplets (and this is clearer from ImageMagick docs)

So from https://doc.qt.io/qt-5/qimage.html#Format-enum the correct choice has to be RGBXXX. Given that the pixels were encoded as "Charpixels" I hazarded a guess that each pixel was represented by one character (that is, an 8-bit "byte") and therefore I wanted the image format with all the eights, hence RGB888.

I hope this helps the next guy :-)

(And yes, in retrospect it seems face-smackingly obvious)

Upvotes: 1

Related Questions