How to make the image background become transparent?
-
Hi,
I want to make the image background become transparent.
The image has a pink background, but I only need the icon.
So is there a way to make the pink become transparent?This is my code, but it does not work:
QPixmap pixmap = QPixmap(":/icon/Manuel López Muñiz/database-normal.bmp");
QPixmap temp(pixmap.size());
temp.fill(Qt::transparent);QPainter p(&temp);
p.setCompositionMode(QPainter::CompositionMode_Source);
p.drawPixmap(0, 0, pixmap);
p.setCompositionMode(QPainter::CompositionMode_SourceOver);
p.fillRect(temp.rect(), QColor(255, 0, 255, 0));
p.end();
pixmap = temp;Thanks for your time.
-
see this https://en.wikipedia.org/wiki/BMP_file_format for a description of the BMP format. It does NOT support alpha channels. If you wish to use transparency then you have two choices:
- use an image format that supports transparencies
- translate the RGB BMP image into a format that replaces the pink pixels with pixels where the alpha value is zero (0) and use that converted image.
-
@Kent-Dorfman Thanks for your reply!
So I tried your suggestion, and this did not work as I expected.
Is any thing wrong with my code?QImage bmp = QImage(":/icon/Manuel López Muñiz/database-normal.bmp");
bmp.convertToFormat(QImage::Format_RGBA8888_Premultiplied);
int width = bmp.width();
int height = bmp.height();
QColor change(255, 0, 255);
QColor want(255, 0, 255, 0);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
if (bmp.pixelColor(i, j) == change)
bmp.setPixelColor(i, j, want);
}
}QPixmap pixmap = QPixmap::fromImage(bmp);
database = new QAction;
QIcon icon(pixmap);
database->setIcon(icon);
ui->mainToolBar->addAction(database); -
have you verified that QColor(0xff00ff) is in fact the color that you need to replace? maybe add a count of pixels that it changes and then inspect that count to see if anything is actually being changed.
Personally, I would have taken the first approach. Use an image editor and edit the BMP file so that it is in the correct format, and uses alpha correctly.