Search code examples
qtrgbqimagepixel-manipulation

How to set QImage pixel colour for an RGB888 image in Qt


I have an RGB888 format qImage defined as follows:

myQrgb = QImage(img_in, width, height, QImage::Format_RGB888);

I wish to alter specific pixel values, so I followed the example here, like so:

QRgb value = qRgb(0, 0, 0);
myQrgb.setPixel(i, j, value);

This, however, always produces a segmentation fault regardless of the values of i and j (e.g. i = j = 2).

I am guessing it is because I am incorrectly using QRgb to manipulate pixels in a QImage::Format_RGB888. What should I do instead?


Solution

  • There are few things you need to confirm:

    1. According to QImage constructor you're using, make sure img_in remains valid throughout the life span of QImage object. By the way, QImage destructor will not delete your data (img_in).

    2. If the pixel position you're setting is not valid coordinate, setPixel()'s behavior is undefined.

    I suspect the first case, img_in is probably vanishing from QImage. You may want to try to create a QImage using other constructor like QImage(10, 10, QImage::Format_RGB888) and play with setPixel().