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;
// }
// QR code image is being rendered from SVG output, not directly from bitmaps or matrices
// QSvgRenderer has internal limits on path complexity or buffer size — hitting
// those leads to the truncation warning.
// QR code image is being rendered from SVG output, not directly from bitmaps or
// matrices QSvgRenderer has internal limits on path complexity or buffer size —
// hitting those leads to the truncation warning.
// If the generated SVG string is too large or malformed, the QSvgRenderer will
// throw warnings.
// 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
{
const int qrSize = qrCode.getSize();
const int scale = size / (qrSize + 2 * border);
QImage image(size, size, QImage::Format_RGB32);
const int totalSize = qrSize + 2 * border;
// Calculate scaling factor to fit requested size
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);
QPainter painter(&image);
painter.setBrush(Qt::black);
painter.setPen(Qt::NoPen);
// Draw each QR module (black square)
for (int y = 0; y < qrSize; ++y)
{
for (int x = 0; x < qrSize; ++x)
{
if (qrCode.getModule(x, y))
{
QRect rect((x + border) * scale, (y + border) * scale, scale, scale);
painter.drawRect(rect);
int xPos = (x + border) * pixelSize;
int yPos = (y + border) * pixelSize;
painter.drawRect(xPos, yPos, pixelSize, pixelSize);
}
}
}