Another QImage::bits() question
-
I have some image data that is held in a private format that I want to copy into a QImage. So I would create the QImage thus:
std::make_shared<QImage>(width, hight, QImage::Format_RGB32);
and then call bits() to get the buffer location to which I then copy and reformat the image data.
To display the image I call QPixmap::fromImage() which I feed to an image viewer widget. That part I know works.
Lets say that some processing is then done on the private image data and the revised data is copied to the location that bits() initially returned, and QPixmap::fromImage() is called to display the current revision. This is would be repeated until the user was happy with the revised image.
Will that work as I expect, or does calling (e.g.) QPixmap::fromImage() result in my working on a different image buffer from the one I think I am using?
Thanks
David -
A call to QImage::bits() always detaches. And you must not store this pointer somewhere to access it later on as it might get a dangling pointer.
-
The only changes I make to the QImage are by writing direct to the buffer. So what could cause that pointer to dangle?? I'd very much prefer not to incur the large cost of a deep copy every time round that process. That's why I proposed caching the result of bits() even though that's not normal practice.
I didn't use the fixed buffer ctor as I didn't want to have to worry about the bookkeeping I'd need to do if I used that. If using QImage::Format_RGB32, is the buffer size always sizeof(QRGB) * width * height?
-
@Perdrix said in Another QImage::bits() question:
QImage::Format_RGB32, is the buffer size always sizeof(QRGB) * width * height?
No, it's 4 byte per pixel internally with alpha = 255
Don't rely on any internals, it might work today but not tomorrow. And storing QImage::bits() pointer is such an internal thing.
Also there is no reaons that QPixmap::fromImage() does not detach (e.g. due to other internal image format, a write access by accident (= calling a non-const function), a programming error or whatever). -
Yes, 4 bytes.
-
You might find this similar thread with similar behind-Qimage's-back-manipulations useful: How to make QImage aware of updated memory buffer?