QT使用QImage做图片切割

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 
#include 

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);


       // 选择本地图片文件
       QString filename = QFileDialog::getOpenFileName(nullptr, "选择图片", "", "Images (*.png *.xpm *.jpg *.bmp)");

       // 读取选中的图片文件
       QImage image(filename);

       // 检查是否成功加载图片
       if (image.isNull()) {
           qDebug() << "图片加载失败";
       }

       // 定义切割的宽度和高度
       int width = image.width() / 2; // 切割后的宽度
       int height = image.height() / 2; // 切割后的高度

       // 创建保存切割后图片的文件夹
       QString folderPath = QDir::currentPath() + "/cutting_image";
       QDir().mkdir(folderPath);

       // 切割并保存图片
       for (int x = 0; x < 2; x++) {
           for (int y = 0; y < 2; y++) {
               // 切割图片
               QImage cImage = image.copy(x * width, y * height, width, height);

               // 保存切割后的图片
               QString cuttingFilename = folderPath + "/cutting_image_" + QString::number(x) + "_" + QString::number(y) + ".png";
               qDebug() << "croppedFilename===="<

这里我使用的是深拷贝,什么叫深拷贝你们可以自行百度一下,我把一张图片平均分成了四份,你们可以按照你们自己的需求更改代码.主要就是:

image.copy(x,y,w,h);

test.png就是原图

QT使用QImage做图片切割_第1张图片

你可能感兴趣的:(qt)