aboutsummaryrefslogtreecommitdiff
path: root/src/QR-Code-scanner/Decoder.cpp
blob: a814969b7613c416e3631759eaef8056af312d17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "Decoder.h"

#include <limits>

#include "quirc.h"

QrDecoder::QrDecoder()
    : m_qr(quirc_new())
{
    if (m_qr == nullptr)
    {
        throw std::runtime_error("QUIRC: failed to allocate memory");
    }
}

QrDecoder::~QrDecoder()
{
    quirc_destroy(m_qr);
}

std::vector<std::string> QrDecoder::decode(const QImage &image)
{
    if (image.format() == QImage::Format_Grayscale8)
    {
        return decodeGrayscale8(image);
    }
    return decodeGrayscale8(image.convertToFormat(QImage::Format_Grayscale8));
}

std::vector<std::string> QrDecoder::decodeGrayscale8(const QImage &image)
{
    if (quirc_resize(m_qr, image.width(), image.height()) < 0)
    {
        throw std::runtime_error("QUIRC: failed to allocate video memory");
    }

    uint8_t *rawImage = quirc_begin(m_qr, nullptr, nullptr);
    if (rawImage == nullptr)
    {
        throw std::runtime_error("QUIRC: failed to get image buffer");
    }
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
    std::copy(image.constBits(), image.constBits() + image.sizeInBytes(), rawImage);
#else
    std::copy(image.constBits(), image.constBits() + image.byteCount(), rawImage);
#endif
    quirc_end(m_qr);

    const int count = quirc_count(m_qr);
    if (count < 0)
    {
        throw std::runtime_error("QUIRC: failed to get the number of recognized QR-codes");
    }

    std::vector<std::string> result;
    result.reserve(static_cast<size_t>(count));
    for (int index = 0; index < count; ++index)
    {
        quirc_code code;
        quirc_extract(m_qr, index, &code);

        quirc_data data;
        const quirc_decode_error_t err = quirc_decode(&code, &data);
        if (err == QUIRC_SUCCESS)
        {
            result.emplace_back(&data.payload[0], &data.payload[data.payload_len]);
        }
    }

    return result;
}