dynamically adjusts the imageSize so that each module is an integer number of pixels, avoiding possible aliasing artifacts when size isn’t divisible evenly by qrSize + 2 × border.

This commit is contained in:
gregory
2025-05-08 20:04:01 -04:00
parent 8be10721ee
commit 594033264e
+13 -9
View File
@@ -126,10 +126,9 @@ QString QrCodeGenerator::toSvgString(const qrcodegen::QrCode &qr,
// return image; // return image;
// } // }
// QR code image is being rendered from SVG output, not directly from bitmaps or
// QR code image is being rendered from SVG output, not directly from bitmaps or matrices // matrices QSvgRenderer has internal limits on path complexity or buffer size —
// QSvgRenderer has internal limits on path complexity or buffer size — hitting // hitting those leads to the truncation warning.
// those leads to the truncation warning.
// If the generated SVG string is too large or malformed, the QSvgRenderer will // If the generated SVG string is too large or malformed, the QSvgRenderer will
// throw warnings. // throw warnings.
// like: W : qt.svg: Invalid path data; path truncated. // like: W : qt.svg: Invalid path data; path truncated.
@@ -137,23 +136,28 @@ QImage QrCodeGenerator::qrCodeToImage(const qrcodegen::QrCode &qrCode,
quint16 border, quint16 size) const quint16 border, quint16 size) const
{ {
const int qrSize = qrCode.getSize(); const int qrSize = qrCode.getSize();
const int scale = size / (qrSize + 2 * border); const int totalSize = qrSize + 2 * border;
// Calculate scaling factor to fit requested size
QImage image(size, size, QImage::Format_RGB32); const int pixelSize = size / totalSize;
const int imageSize = pixelSize * totalSize;
// Create the output image
QImage image(imageSize, imageSize, QImage::Format_RGB32);
image.fill(Qt::white); image.fill(Qt::white);
QPainter painter(&image); QPainter painter(&image);
painter.setBrush(Qt::black); painter.setBrush(Qt::black);
painter.setPen(Qt::NoPen); painter.setPen(Qt::NoPen);
// Draw each QR module (black square)
for (int y = 0; y < qrSize; ++y) for (int y = 0; y < qrSize; ++y)
{ {
for (int x = 0; x < qrSize; ++x) for (int x = 0; x < qrSize; ++x)
{ {
if (qrCode.getModule(x, y)) if (qrCode.getModule(x, y))
{ {
QRect rect((x + border) * scale, (y + border) * scale, scale, scale); int xPos = (x + border) * pixelSize;
painter.drawRect(rect); int yPos = (y + border) * pixelSize;
painter.drawRect(xPos, yPos, pixelSize, pixelSize);
} }
} }
} }