Coffee_Candy

176 分类: nodejs后端开发,Qt软件开发

QT6多线程image转base64编码

学过C++的都知道,这玩意是单线工作的

如果遇到需要长时间处理的代码块会直接卡死在那部分(比如说把一张图片转base64码后上传服务器)
和nodejs的异步io差别很大,nodejs的强异步可以让通信和io操作宏观上分离,微观上并发,提高体验效果
(当然如果想要更好的效果肯定是写多线程会好点)
但是C++不行,你必须得写多线程与主线程分离

对于在QT中如何写一个多线程

QT中提供了QThread,我们只需要去继承他去重写run的虚函数后,调用start就行
然后也因此引伸出另一个问题,如何在主线程收到子线程中的数据(可以用信号槽连接通信)
然后又引伸出另一个问题如何保证在子线程运行完前,子线程不会被销毁掉(用share_ptr)

子线程的.h定义

#include <Qthread>
#include "global.h"
class Imagethread:public QThread,std::enable_shared_from_this<Imagethread>
{
    Q_OBJECT
public:
    Imagethread(const QStringList imagelist,QObject *parent=nullptr);
    ~Imagethread();
    QStringList* imageswitchbase64();
protected:
    virtual void run();//主要是重写这个run
private:
    QStringList* imagebase64list;//管理子线程得出的数据
    bool _bstop=false;
    QStringList imagelist;
signals:
    void SigFinishImageSwitchBase64(QStringList* imagebase64list);
};

.cpp实现

#include "Imagethread.h"
#include <QBuffer>
#include <QPixmap>
Imagethread::Imagethread(const QStringList imagelist, QObject* parent):
    QThread(parent),imagelist(imagelist)
{
}

Imagethread::~Imagethread()
{
    delete imagebase64list;
}

QStringList* Imagethread::imageswitchbase64()
{
    imagebase64list = new QStringList();
    if (this->imagelist.size() > 0)
    {
        for (QString imageurl : this->imagelist)
        {
            QPixmap tpimage(imageurl);
            QByteArray byteArray;
            QBuffer buffer(&byteArray);
            buffer.open(QIODevice::WriteOnly);
            tpimage.save(&buffer, "PNG");
            QString base64Data = byteArray.toBase64();
            imagebase64list->append(base64Data);
            qDebug() <<"size:" << imagebase64list->size();
        }
        return imagebase64list;
    }
    return nullptr;
}

void Imagethread::run()
{
    qDebug() << "run";
    QStringList* imagebase64list=imageswitchbase64();
    if (imagebase64list != nullptr)
    {
        qDebug() << "size:" << imagebase64list->size();
    }
    if (_bstop)
    {
        delete imagebase64list;
        return;
    }
    emit SigFinishImageSwitchBase64(imagebase64list);
}

调用的地方如何操作

2024-10-24T09:32:59.png
2024-10-24T09:35:34.png

#none

作者: Coffee_Candy

版权: 除特别声明,均采用BY-NC-SA 4.0许可协议,转载请表明出处

目录Content

评论已关闭