zoukankan      html  css  js  c++  java
  • 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修改图片的背景色及设置背景色为透明的方法

  • 相关阅读:
    用 Web 实现一个简易的音频编辑器
    TypeScript教程
    他的独,殇情沉醉
    重新拎一遍js的正则表达式
    网络流
    Xmind最新的安装与破解教程
    adb的端口号5037被占用的解决方法
    使用Fiddler模拟弱网测试教程
    web的前台、后台、前端、后端
    常见面试笔试题
  • 原文地址:https://www.cnblogs.com/2018shawn/p/11429386.html
Copyright © 2011-2022 走看看