Subclass QIODevice
to allow saving an image into a std::vector<char>
.
It can be useful for example when using cv::imdecode.
Usage:
QImage src("myImage.png");
CharVectorDevice myIODevice;
src.save(&myIODevice, "PNG", 100);
Subclass QIODevice
to allow saving an image into a std::vector<char>
.
It can be useful for example when using cv::imdecode.
Usage:
QImage src("myImage.png");
CharVectorDevice myIODevice;
src.save(&myIODevice, "PNG", 100);
#include <QIODevice> | |
#include <vector> | |
#include <algorithm> | |
struct CharVectorDevice : public QIODevice | |
{ | |
public: | |
virtual bool seek(qint64 pos) | |
{ | |
if (pos < 0 || pos > static_cast<qint64>(m_vector.size())) { | |
qWarning("CharVectorDevice::seek: Invalid pos: %d", int(pos)); | |
return false; | |
} | |
m_ioIndex = static_cast<int>(pos); | |
return QIODevice::seek(pos); | |
} | |
std::vector<char>& GetVector() | |
{ | |
return m_vector; | |
} | |
protected: | |
virtual qint64 readData(char *data, qint64 len) | |
{ | |
if ((len = qMin(len, static_cast<qint64>(m_vector.size()) - m_ioIndex)) | |
<= 0) { | |
return qint64(0); | |
} | |
std::copy(m_vector.cbegin() + m_ioIndex, m_vector.cbegin() + len, data); | |
m_ioIndex += static_cast<int>(len); | |
return len; | |
} | |
virtual qint64 writeData(const char *data, qint64 len) | |
{ | |
const int overflow = static_cast | |
<int>(m_ioIndex + len - m_vector.size()); | |
if (overflow > 0) { | |
m_vector.resize(m_ioIndex + len); | |
} | |
std::copy(data, data + len, m_vector.begin() + m_ioIndex); | |
m_ioIndex += static_cast<int>(len); | |
return len; | |
} | |
int m_ioIndex; | |
std::vector<char> m_vector; | |
}; |