Qt修改圖片的背景色及設置背景色為透明的方法


先上干貨。

Qt下修改圖片背景色的方法:

方法一:

QPixmap CKnitWidget::ChangeImageColor(QPixmap sourcePixmap, QColor origColor, QColor destColor)
{
QImage image = sourcePixmap.toImage();
for(int w = 0;w < image.width();++w)
for(int h = 0; h < image.height();++h)
{
QRgb rgb = image.pixel(w,h);
if(rgb == origColor.rgb())
{
///替換顏色
image.setPixel(w,h,destColor.rgba());
}
}
return QPixmap::fromImage(image);
}

 


這是非常暴力的方法,但是非常有用,經測試,位深度24及以上的圖片都能被修改。

方法二:

QPixmap Widget::ChangeImageColor(QPixmap sourcePixmap, QColor origColor, QColor destColor)
{
QImage image = sourcePixmap.toImage();
uchar * imagebits_32;
for(int i =0; i <image.height(); ++i)
{
imagebits_32 = image.scanLine(i);
for(int j =0; j < image.width(); ++j)
{
int r_32 = imagebits_32[j * 4 + 2];
int g_32 = imagebits_32[j * 4 + 1];
int b_32 = imagebits_32[j * 4];
if(r_32 == origColor.red()
&& g_32 == origColor.green()
&& b_32 == origColor.blue())
{
imagebits_32[j * 4 + 2] = (uchar)destColor.red();
imagebits_32[j * 4 + 1] = (uchar)destColor.green();
imagebits_32[j * 4] = (uchar)destColor.blue();
}
}
}
return QPixmap::fromImage(image);
}

 


 

相對開銷小一點的方法,但在圖片量不大的情況下,CPU處理起來都挺快。

 

 

 

 

  原理都是替換指定像素區域的色碼,但是Qt文檔推薦方法一,相對開銷較小。具體原理還有很多的,先貼出來,跟大家一起學習。有時候方法一無效,但是方法二有效,都可以試試。

    圖片背景色設為透明的方法:

 

///將指定圖片的指定顏色扣成透明顏色的方法

QImage Widget::ConvertImageToTransparent(QImage image/*QPixmap qPixmap*/)
{
image = image.convertToFormat(QImage::Format_ARGB32);
union myrgb
{
uint rgba;
uchar rgba_bits[4];
};
myrgb* mybits =(myrgb*) image.bits();
int len = image.width()*image.height();
while(len --> 0)
{
mybits->rgba_bits[3] = (mybits->rgba== 0xFF000000)?0:255;
mybits++;
}
return image;
}

 


 

原理其實就是設置圖片的alpha通道為0,即全透明。
這里有個注意點:
如果需要保存透明圖片要注意選用支持alpha通道的圖片格式,一般選用png格式。



原文鏈接:

Qt修改圖片的背景色及設置背景色為透明的方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM