How to set opacity of a QImage
-
Hi,
AFAIK, you would need to use an ARGB format. Then it depends on what you are currently doing with that QImage, painting ?
-
I have a QLabel with a QImage (base image ) and I want to drag others QImage on this( anomaly image like triangle, circle, square, etc). During dropEvent, I copy all pixels of the anomaly image on the base image into the rectangle where it is dropped. So I save a finally image which is the baseImage containing the anomaly.
Currently I can set opacity of the default image pasted on the base image, I can see it directly, this is my function.
@void AjoutDefaut::opacity(QImage& image)
{
m_method = 9;
showSliders();
if ( m_A>255 || m_A<0 )
{
m_A=50;
}
QPixmap transparent(image.size());
transparent.fill(Qt::transparent);
QPainter p;p.begin(&transparent); p.setCompositionMode(QPainter::CompositionMode_Source); p.drawPixmap(0, 0, QPixmap::fromImage(image)); p.setCompositionMode(QPainter::CompositionMode_DestinationIn); p.fillRect(transparent.rect(), QColor(0, 0, 0, m_A)); p.end(); image = transparent.toImage(); loadImage(image); //m_currentAnomaly = image; repaint();}@
I have the result that I want. ( transparency setted )
And, this is my function which save now the image after setting the anomaly opacity:
@
QImage DragWidgetCible::insertAnomaly( QImage base )
{
QImage result = QImage();
result = base.copy(0, 0, base.width(), base.height());
result.convertToFormat(QImage::Format_ARGB32);
for(int elem=0; elem<m_anomalyContainer.size(); elem++)
{
m_anomalyContainer[elem].getAnomaly().convertToFormat(QImage::Format_ARGB32);
binariseAnomaly(m_anomalyContainer[elem].getAnomaly(), 1);
int width = m_anomalyContainer[elem].getAnomaly().width();
int height = m_anomalyContainer[elem].getAnomaly().height();
QPoint p(m_anomalyContainer[elem].getAnomalyPos());for(int i=p.x(),k=0; i<p.x()+width, k<width; i++,k++) { for(int j=p.y(), l=0; j<p.y()+height, l<height; j++, l++) { QRgb x = m_anomalyContainer[elem].getAnomaly().pixel(k, l); qDebug() << qGray(x); if(!m_opacityUpdated) { if (qAlpha(x) != 0 && (qGray(x) != 255)) { result.setPixel(i, j, x); } } else (// we are in this case because m_opacityUpdated = true ) { result.setPixel(i, j, x); m_opacityUpdated = false; } } }}
return result;
}@BUT, when I see the final saved image, I have another kind of opacity: a dark image, and when the opacity is setted to 0, the anomaly is black.
-
This works for me. I hope helps
@QImage image;
image.load(":/images/ok.png");
//If the image doesn't have set the alpha chanel
image = image.convertToFormat(QImage::Format_ARGB32);
//...QImage image2;
image2 = setOpacity(image, 0.5);
//...QImage setOpacity(QImage& image, qreal opacity)
{
QImage newImg(image.size(), QImage::Format_ARGB32);
newImg.fill(Qt::transparent);QPainter painter(&newImg); painter.setOpacity(opacity); painter.drawImage(QRect(0, 0, image.width(), image.height()), image); return newImg;}@