PDA

View Full Version : How to change QPixmap color from black to red



oogolov
29th March 2012, 14:46
I have png-file in black/white color.

QPixmap bearingPixmap;
bearingPixmap.load(":/Hinge.png");

How to change QPixmap black color to red?
In which way can I use createMaskFromColor and setMask?

wysota
29th March 2012, 14:51
If the image is index coloured then the easiest option is to change the colour map.

oogolov
29th March 2012, 16:07
I don't know what is index coloured image.
I'd like set this pixmap
7539
to my QGraphicsPixmapItem.
Then I want to change black color to red after picking the item.
I don't like to create one more red png-file.

wysota
29th March 2012, 17:56
I don't know what is index coloured image.
It's an image that has at most 8 bits per colour (meaning a maximum of 256 colours) as opposed to 24 or 32bit.


I'd like set this pixmap
7539
to my QGraphicsPixmapItem.
It's not an indexed image but you can convert it to one using gimp, imagemagick or any other graphics tool available.

Then you can use QImage::setColorTable() to set a new colour map for the image.

Spitfire
30th March 2012, 17:13
try


QPixmap px( "C:\\Hinge.png" );
QPixmap pxr( px.size() );
pxr.fill( Qt::red );
pxr.setMask( px.createMaskFromColor( Qt::transparent ) );

You will get: 7543

Maybe not the most elengant way (and definitely not the fastest) but does the job.

ehopperdietzel
18th August 2017, 22:08
@Spitfire's code works good for flat images.
If your image has varying alpha values you can use:


QImage tmp = pixmap.toImage();

for(int y = 0; y < tmp.height(); y++)
for(int x= 0; x < tmp.width(); x++)
color.setAlpha(tmp.pixelColor(x,y).alpha());
tmp.setPixelColor(x,y,color);

pixmap = QPixmap::fromImage(tmp);

Commented:




// "pixmap" is your QPixmap
// "color" is your QColor

// Convert the pixmap to QImage
QImage tmp = pixmap.toImage();

// Loop all the pixels
for(int y = 0; y < tmp.height(); y++)
{
for(int x= 0; x < tmp.width(); x++)
{
// Read the alpha value each pixel, keeping the RGB values of your color
color.setAlpha(tmp.pixelColor(x,y).alpha());

// Apply the pixel color
tmp.setPixelColor(x,y,color);
}
}

// Get the coloured pixmap
pixmap = QPixmap::fromImage(tmp);

asgawa
12th October 2017, 09:03
This works since 5.6
http://doc.qt.io/qt-5/qimage.html#pixelColor