先上干货。学习
Qt下修改图片背景色的方法:测试
方法一:ui
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及以上的图片都能被修改。spa
方法二:.net
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处理起来都挺快。code
原理都是替换指定像素区域的色码,可是Qt文档推荐方法一,相对开销较小。具体原理还有不少的,先贴出来,跟你们一块儿学习。有时候方法一无效,可是方法二有效,均可以试试。orm
图片背景色设为透明的方法:blog
///将指定图片的指定颜色扣成透明颜色的方法图片
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格式。文档
原文连接: