Two methods of traversing pixel maps are mainly used here
One is to modify the RGBA color by accessing pixels through memory
The other is to use the setPixelColor() function to access each pixel to modify the color
1. Open QT and create a widget project
Preset the widget window to 1280 * 720 corresponding to the space opened up by QImage in the code
2. Code demonstration The header file is not included for space reasons, the following codes are all in widget.cpp
The header file needs to declare void paintEvent(QPaintEvent *ev) and QImage img ;
#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
// 为图片开辟一个像素空间
img = QImage(1280,720,QImage::Format_RGBA8888);
// 填充颜色
img.fill(QColor(0,0,255,250));
// 通过遍历,设置颜色
// 通过访问内存进行遍历 遍历上像素图的半部分
uchar *uc = img.bits();
int wid = img.width(); // 先计算出当前行,遍历的时候就用每次都调用 width() 函数了
for(int i = 0 ; i < img.width();i ++)
{
for(int j = 0 ; j < img.height() / 2; j ++)
{
// 从每行开始,每列的像素颜色设置成 RGBA
uc[j*wid * 4 + i * 4] = 255; // R
uc[j*wid * 4 + i * 4 + 1] = 0; // G
uc[j*wid * 4 + i * 4 + 1] = 0; // B
uc[j*wid * 4 + i * 4 + 1] = 100; // A
}
}
// 用直接写入像素点颜色的方式遍历 遍历像素图的上半部分的右半部分
for(int i = img.width() / 2 ; i < img.width();i ++)
{
for(int j = 0 ; j < img.height() / 2; j ++)
{
img.setPixelColor(i,j,QColor(25,25,112,250));
}
}
// 像素图的右下部分
for(int i = img.width() / 2 ; i < img.width();i ++)
{
for(int j = img.height()/ 2 ; j < img.height(); j ++)
{
img.setPixelColor(i,j,QColor(112,128,144,250));
}
}
}
void Widget::paintEvent(QPaintEvent *ev)
{
QPainter p(this);
// 图片为空就直接结束,防止宕机
if(img.isNull()) return;
// 绘制图片
p.drawImage(0,0,img);
}
Widget::~Widget()
{
delete ui;
}
3. Demonstration effect
I want it all.jpg