Small snippet showing how to take a QImage, run through its pixels and modify them based on certain conditions.

Here img is an input image, the application form has 4 checkboxes, which define the component of the color (ARGB) that is to be masked.

  1.     // img is the input original image
  2.     QRect rect = img->rect();
  3.     QImage *result = new QImage(wd, ht, img->format());
  4.     uint *output=0, *input = 0;
  5.     for (int y = rect.top(); y < rect.bottom(); y++)
  6.     {
  7.         input = (uint*)img->scanLine(y - rect.top());
  8.         output = (uint*)result->scanLine(y - rect.top());
  9.         for (int x = rect.left(); x < rect.right(); x++)
  10.         {
  11.             int col = *input;
  12.             if (col == Qt::transparent || col == Qt::color0)
  13.             {
  14.                 *output++ = *input++;
  15.                 continue;
  16.             }
  17.             QColor qcol = QColor::fromRgba(col);
  18.             if (ui->redBox->checkState() == 0) qcol.setRed(0);
  19.             if (ui->greenBox->checkState() == 0) qcol.setGreen(0);
  20.             if (ui->blueBox->checkState() == 0) qcol.setBlue(0);
  21.             if (ui->alphaBox->checkState() == 0) qcol.setAlpha(0);
  22.             *output++ = qcol.rgba();
  23.             input++;
  24.         }
  25.     }
  26.     // At this point result will have the modified QImage

Here is an alternative version which should be quite a bit faster, but is less readable, perhaps:

  1.     // img is the input original image
  2.     QRect rect = img->rect();
  3.     QImage *result = new QImage(wd, ht, img->format());
  4.     // Mask is suitable for colors in ARGB byte order.
  5.     uint mask = 0;
  6.     if (ui->redBox->checkState() != 0)
  7.         mask = mask | 0x00ff0000;
  8.     if (ui->greenBox->checkState() != 0)
  9.         mask = mask | 0x0000ff00;
  10.     if (ui->blueBox->checkState() != 0)
  11.         mask = mask | 0x000000ff;
  12.     if (ui->alphaBox->checkState() != 0)
  13.         mask = mask | 0xff000000;
  14.     for (int y = rect.top(); y < rect.bottom(); y++)
  15.     {
  16.         uint* input = (uint*)img->scanLine(y - rect.top());
  17.         uint* output = (uint*)result->scanLine(y - rect.top());
  18.         for (int x = rect.left(); x < rect.right(); x++)
  19.         {
  20.             *output = *input & mask;
  21.             output++;
  22.             input++;
  23.         }
  24.     }
  25.     // At this point result will have the modified QImage

Categories: