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格式。
欢迎各位指正,顺便吐槽下,csdn这个写博客的功能真的很难受,有的字打不上来,但是可以粘贴上来。。



猜你喜欢

转载自blog.csdn.net/daizhiyan1/article/details/79026573