File indexing completed on 2024-05-12 15:49:08
0001 /* 0002 SPDX-FileCopyrightText: 2010-2014 Sune Vuorela <sune@vuorela.dk> 0003 0004 SPDX-License-Identifier: MIT 0005 */ 0006 0007 #include "datamatrixbarcode.h" 0008 #include <dmtx.h> 0009 using namespace Prison; 0010 0011 DataMatrixBarcode::DataMatrixBarcode() 0012 : AbstractBarcode(AbstractBarcode::TwoDimensions) 0013 { 0014 } 0015 DataMatrixBarcode::~DataMatrixBarcode() = default; 0016 0017 QImage DataMatrixBarcode::paintImage(const QSizeF &size) 0018 { 0019 Q_UNUSED(size); 0020 if (data().size() > 1200) { 0021 return QImage(); 0022 } 0023 0024 DmtxEncode *enc = dmtxEncodeCreate(); 0025 dmtxEncodeSetProp(enc, DmtxPropPixelPacking, DmtxPack32bppRGBX); 0026 dmtxEncodeSetProp(enc, DmtxPropModuleSize, 1); 0027 dmtxEncodeSetProp(enc, DmtxPropMarginSize, 2); 0028 0029 QByteArray trimmedData(data().trimmed().toUtf8()); 0030 DmtxPassFail result = dmtxEncodeDataMatrix(enc, trimmedData.length(), reinterpret_cast<unsigned char *>(trimmedData.data())); 0031 if (result == DmtxFail) { 0032 dmtxEncodeDestroy(&enc); 0033 return QImage(); 0034 } 0035 Q_ASSERT(enc->image->width == enc->image->height); 0036 0037 QImage ret; 0038 0039 if (foregroundColor() == Qt::black && backgroundColor() == Qt::white) { 0040 QImage tmp(enc->image->pxl, enc->image->width, enc->image->height, QImage::Format_ARGB32); 0041 // we need to copy, because QImage generated from a char pointer requires the 0042 // char pointer to be kept around forever, and manually deleted. 0043 ret = tmp.copy(); 0044 } else { 0045 if (enc->image->width > 0) { 0046 int size = enc->image->width * enc->image->height * 4; 0047 uchar *img = new uchar[size]; 0048 QByteArray background(4, '\0'); 0049 background[3] = qAlpha(backgroundColor().rgba()); 0050 background[2] = qRed(backgroundColor().rgba()); 0051 background[1] = qGreen(backgroundColor().rgba()); 0052 background[0] = qBlue(backgroundColor().rgba()); 0053 QByteArray foreground(4, '\0'); 0054 foreground[3] = qAlpha(foregroundColor().rgba()); 0055 foreground[2] = qRed(foregroundColor().rgba()); 0056 foreground[1] = qGreen(foregroundColor().rgba()); 0057 foreground[0] = qBlue(foregroundColor().rgba()); 0058 for (int i = 1; i < size; i += 4) { 0059 QByteArray color; 0060 if (enc->image->pxl[i] == 0x00) { 0061 color = foreground; 0062 } else { 0063 color = background; 0064 } 0065 for (int j = 0; j < 4; j++) { 0066 img[i - 1 + j] = color[j]; 0067 } 0068 } 0069 QImage tmp(img, enc->image->width, enc->image->height, QImage::Format_ARGB32); 0070 // we need to copy, because QImage generated from a char pointer requires the 0071 // char pointer to be kept around forever, and manually deleted. 0072 ret = tmp.copy(); 0073 delete[] img; 0074 } 0075 } 0076 dmtxEncodeDestroy(&enc); 0077 return ret; 0078 }