qzxing/src/imagehandler.cpp

94 lines
2.5 KiB
C++
Raw Normal View History

#include "imagehandler.h"
#include <QGraphicsObject>
#include <QImage>
#include <QPainter>
#include <QStyleOptionGraphicsItem>
#include <QDebug>
2016-09-15 13:22:08 +03:00
#include <QQuickItem>
#include <QQuickItemGrabResult>
#include <QQuickWindow>
#include <QThread>
#include <QTime>
ImageHandler::ImageHandler(QObject *parent) :
QObject(parent)
{
}
2016-09-15 13:22:08 +03:00
QImage ImageHandler::extractQImage(QObject *imageObj, int offsetX, int offsetY, int width, int height)
{
2016-09-15 13:22:08 +03:00
#if QT_VERSION >= 0x050000
QQuickItem *item = qobject_cast<QQuickItem *>(imageObj);
if (!item || !item->window()->isVisible()) {
qDebug() << "Item is NULL";
return QImage();
}
QTime timer;
timer.start();
2016-09-27 15:38:33 +03:00
QSharedPointer<QQuickItemGrabResult> result = item->grabToImage();
pendingGrabbersLocker.lockForWrite();
pendingGrabbers << result.data();
pendingGrabbersLocker.unlock();
connect(result.data(), &QQuickItemGrabResult::ready, this, &ImageHandler::imageGrabberReady);
while (timer.elapsed() < 1000) {
pendingGrabbersLocker.lockForRead();
if (!pendingGrabbers.contains(result.data())) {
pendingGrabbersLocker.unlock();
break;
}
pendingGrabbersLocker.unlock();
2016-09-15 13:22:08 +03:00
qApp->processEvents();
QThread::yieldCurrentThread();
}
2016-09-27 15:38:33 +03:00
QImage img = result->image();
2016-09-15 13:22:08 +03:00
#else
QGraphicsObject *item = qobject_cast<QGraphicsObject*>(imageObj);
if (!item) {
qDebug() << "Item is NULL";
return QImage();
}
QImage img(item->boundingRect().size().toSize(), QImage::Format_RGB32);
img.fill(QColor(255, 255, 255).rgb());
QPainter painter(&img);
QStyleOptionGraphicsItem styleOption;
item->paint(&painter, &styleOption);
2016-09-15 13:22:08 +03:00
#endif
2016-09-15 13:22:08 +03:00
if (offsetX < 0)
offsetX = 0;
if (offsetY < 0)
offsetY = 0;
if (width < 0)
width = 0;
if (height < 0)
height = 0;
if (offsetX || offsetY || width || height)
2016-09-27 15:38:33 +03:00
return img.copy(offsetX, offsetY, width, height);
else
2016-09-27 15:38:33 +03:00
return img;
}
void ImageHandler::save(QObject *imageObj, const QString &path,
2016-09-15 13:22:08 +03:00
const int offsetX, const int offsetY,
const int width, const int height)
{
QImage img = extractQImage(imageObj, offsetX, offsetY, width, height);
img.save(path);
}
2016-09-27 15:38:33 +03:00
#if QT_VERSION >= 0x050000
void ImageHandler::imageGrabberReady()
{
pendingGrabbersLocker.lockForWrite();
pendingGrabbers.remove(sender());
pendingGrabbersLocker.unlock();
}
#endif