效果图
指数5
指数15
指数40
原理
马赛克的原理很简单,就是取一个值,让这个值作为一个方格子的长宽,如40*40px的格子,取这个区域的平均R G B值,然后这个区域的所有像素点都是这个RGB值即可
源码
QImage applyMosaic(const QImage& oldImage, int blockSize) {
if (oldImage.isNull() || blockSize <= 0) {
return QImage(); // 返回空图片或处理错误
}
// 确保blockSize是偶数,并且不会使图像尺寸变得太小
blockSize = (blockSize % 2 == 0) ? blockSize : blockSize + 1;
if (oldImage.width() < blockSize || oldImage.height() < blockSize) {
return oldImage; // 如果blockSize太大,直接返回原图
}
// 计算新图片的尺寸
int newWidth = oldImage.width() / blockSize * blockSize;
int newHeight = oldImage.height() / blockSize * blockSize;
QImage newImage(newWidth, newHeight, oldImage.format());
// 遍历每个块
for (int y = 0; y < newHeight; y += blockSize) {
for (int x = 0; x < newWidth; x += blockSize) {
// 计算块的平均颜色
QRgb averageColor = qRgb(0, 0, 0); // 初始化平均颜色为黑色
int totalR = 0, totalG = 0, totalB = 0;
int count = 0;
for (int by = 0; by < blockSize && y + by < oldImage.height(); ++by) {
for (int bx = 0; bx < blockSize && x + bx < oldImage.width(); ++bx) {
QRgb pixel = oldImage.pixel(x + bx, y + by);
totalR += qRed(pixel);
totalG += qGreen(pixel);
totalB += qBlue(pixel);
++count;
}
}
if (count > 0) { // 确保count不是0,避免除以0
averageColor = qRgb(totalR / count, totalG / count, totalB / count);
}
// 用平均颜色填充整个块
for (int by = 0; by < blockSize && y + by < newImage.height(); ++by) {
for (int bx = 0; bx < blockSize && x + bx < newImage.width(); ++bx) {
newImage.setPixel(x + bx, y + by, averageColor);
}
}
}
}
return newImage;
}