Beispiel #1
0
def generateCode(article, week, lot):
    #function returns QPicture object containing DataMatrix code with given article, week, lot
    toBeEncoded = 'S/N %s, Lot %s, Date %s' % (article, lot, week)
    bar = toBeEncoded.encode('utf-8')
    encoded_bar = dmtx.encode(bar)
    img = Image.frombytes('RGB', (encoded_bar.width, encoded_bar.height),
                          encoded_bar.pixels)
    img = img.resize(qr_size)
    qimg = ImageQt(img)

    picture = QPicture()
    painter = QPainter()
    painter.begin(picture)

    if frame_options['pen-color'] != Qt.Qt.white:
        painter.setBrush(QBrush(Qt.Qt.white))
    painter.setFont(QFont(font['family'], font['size'], font['weight']))
    if frame_options['pen-color'] != Qt.Qt.white:
        old_pen = painter.pen()
        painter.setPen(
            QPen(frame_options['pen-color'], frame_options['pen-width']))
        painter.drawRoundedRect(0, 0, *label_size, frame_options['radius'],
                                frame_options['radius'])
        painter.setPen(old_pen)
    painter.drawText(*item_positions['article'], "S/N " + article)
    painter.drawText(*item_positions['week'], "Date " + week)
    painter.drawText(*item_positions['lot'], "Lot " + lot)
    painter.drawImage(*item_positions['code'], qimg)

    painter.end()
    return picture
def main(args=None):
    if args is None:
        args = sys.argv[1:]

    parser = argparse.ArgumentParser(
        description='Writes a datamatrix barcode to a new image file')
    parser.add_argument('file', help='Filename of the output image')
    parser.add_argument('data',
                        help='Data to be written; will be utf-8 encoded')
    parser.add_argument(
        '--size',
        help="Encoding size (not image dimensions); default is 'ShapeAuto'",
        choices=ENCODING_SIZE_NAMES)
    parser.add_argument('--scheme',
                        help="Encoding method; default is 'Ascii'",
                        choices=ENCODING_SCHEME_NAMES)
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s ' + pylibdmtx.__version__)
    args = parser.parse_args(args)

    from PIL import Image

    encoded = encode(args.data.encode('utf-8'),
                     size=args.size,
                     scheme=args.scheme)
    im = Image.frombytes('RGB', (encoded.width, encoded.height),
                         encoded.pixels)
    im.save(args.file)
def get_image(data='Some text'):
    encoded = encode(data)
    img = Image.frombytes('RGB', (encoded.width, encoded.height),
                          encoded.pixels)
    filename = data + '.png'
    img.save(filename)
    return filename
Beispiel #4
0
    def test_encode_defaults(self):
        data = b'hello world'
        encoded = encode(data)

        # Check returned data, with the exception of the pixel data
        self.assertEqual(Encoded(width=100, height=100, bpp=24, pixels=None),
                         encoded._replace(pixels=None))
        self._assert_encoded_data(data, encoded)
Beispiel #5
0
def barcode(request, uuid):
    #TODO Do this ONCE and cache the result
    from pylibdmtx.pylibdmtx import encode
    from PIL import Image
    encoded = encode(str(uuid).encode('utf-8'), 'Ascii')
    img = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels)
    response = HttpResponse(content_type="image/png")
    img.save(response, "PNG")
    return response
Beispiel #6
0
async def data_matrix_image_generate(data_gen: DataMatrix):
    message_filename = "./datamatrix/" + data_gen.data_matrix_message.replace(
        '/', '') + ".png"

    encoded = encode(data_gen.data_matrix_message.encode('utf-8'))
    img = Image.frombytes('RGB', (encoded.width, encoded.height),
                          encoded.pixels)
    img.save(message_filename)
    return FileResponse(message_filename)
Beispiel #7
0
def save_image(data_to_encode):
    path_to_image = os.getcwd() + '/media/codes/' + data_to_encode + '.png'
    path_to_resized_image = os.getcwd(
    ) + '/media/codes/' + data_to_encode + '_resize.png'
    encoded = encode(data_to_encode.encode("utf8"))
    img = Image.frombytes("RGB", (encoded.width, encoded.height),
                          encoded.pixels)
    img.save(path_to_image)
    scale_image(path_to_image, path_to_resized_image, 60, 60)
    return path_to_resized_image
    def gen_img(self, code_type, code):
        if code_type == 0:
            EAN = barcode.get_barcode_class('ean13')
            ean = EAN(str(code), writer=ImageWriter())
            ean.save('pics/1D/%s' % code)  ### GENERATOR FUNCTION

        if code_type == 1:
            encoded = pylibdmtx.encode(code)
            img = Image.frombytes('RGB', (encoded.width, encoded.height),
                                  encoded.pixels)
            img.save('pics/2D/%s.png' % code)  ### GENERATOR FUNCTION
Beispiel #9
0
def creating_datamatrix(item_order, order_file, img_path, lable):
    order = open(item_order)
    reader = csv.reader(order, delimiter='\t')
    file_name = 0
    # index_file = open(r'project/index.html', 'w+')
    order_file.write('''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://fonts.googleapis.com/css?family=PT+Sans&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
    <title>Document</title>
</head>
<body>

    <div class="container">''' + '\n')
    for row in reader:
        file_name = file_name + 1
        encoded = encode(" ".join(row).encode('utf8'))
        print(" ".join(row).encode('utf8'))
        gtn = re.findall(r'(?<=01)(.*?)(?=21)',
                         str(" ".join(row).encode('utf8')))
        print(" ".join(gtn))
        serial_number = re.findall(r'(?<=21)(.*)(?=x1d91)',
                                   str(" ".join(row).encode('utf8')))
        serial_number = str(" ".join(serial_number))
        serial_number = serial_number.replace('\\', ' ')
        serial_number = serial_number.replace('<', '&lt;')
        print(serial_number)
        img = Image.frombytes('RGB', (encoded.width, encoded.height),
                              encoded.pixels)
        img.save(img_path + '/' + str(file_name) + '.png')
        order_file.write('''
        <div class="layout">
            <div class="img-wrapper">
                <img src="''' + 'img/' + str(file_name) + '.png' +
                         '''" alt="datamatrix BarCode">
            </div>
            <div class="data-wrapper">
                <p> ''' + lable + '''</p>
                <p class="number">(01) ''' + str(" ".join(gtn)) + '''</p>
                <p class="number">(21) ''' + serial_number + '''</p>
            </div>
        </div>''' + '\n')
    order_file.write('''
    </div>

</body>
</html>
''')
Beispiel #10
0
def qr_generator(data: list, prefix='', suffix=''):
    '''Generate qr codes for data provided, returns tuple of tuples,
    with value and barcode object'''
    qrs = []
    for item in data:
        item_text = prefix + item + suffix
        encoded = encode(item_text.encode('utf-8'))
        qr = Image.frombytes(
            'RGB',
            (encoded.width, encoded.height),
            encoded.pixels
        )

        qrs.append({'data': item_text, 'qr': qr})

    return(qrs)
Beispiel #11
0
    def recalc(self):
        if not self._recalc: return
        data = self._value
        size = self._size
        encoding = self._encoding
        e = pylibdmtx.encode(data, size=size, scheme=encoding)
        iW = e.width
        iH = e.height
        p = e.pixels
        iCellSize = 5
        bpp = 3  #bytes per pixel
        rowLen = iW * bpp
        cellLen = iCellSize * bpp
        assert len(p) // rowLen == iH
        matrix = list(
            filter(None, (''.join(
                (('x' if p[j:j + bpp] != b'\xff\xff\xff' else ' ')
                 for j in range(i, i + rowLen, cellLen))).strip()
                          for i in range(0, iH * rowLen, rowLen * iCellSize))))
        self._nRows = len(matrix)
        self._nCols = len(matrix[-1])
        self._matrix = '\n'.join(matrix)

        cellWidth = self._cellSize
        if cellWidth:
            cellWidth = cellWidth.split('x')
            if len(cellWidth) > 2:
                raise ValueError(
                    'cellSize needs to be distance x distance not %r' %
                    self._cellSize)
            elif len(cellWidth) == 2:
                cellWidth, cellHeight = cellWidth
            else:
                cellWidth = cellHeight = cellWidth[0]
            cellWidth = _numConv(cellWidth)
            cellHeight = _numConv(cellHeight)
        else:
            cellWidth = cellHeight = iCellSize
        self._cellWidth = cellWidth
        self._cellHeight = cellHeight
        self._recalc = False
        self._bord = max(self.border, cellWidth, cellHeight)
        self._width = cellWidth * self._nCols + 2 * self._bord
        self._height = cellHeight * self._nRows + 2 * self._bord
Beispiel #12
0
def generate_datamatrix(exam_token, page_num, copy_num):
    """
    Generates a DataMatrix code to be used on a page.

    To ensure the page information fits into the datamatrix grid, adhere to
    (# of letters in exam ID) + 2 * (# of digits in exam ID) = C for a certain
    constant C. The reason for this is that pylibdmtx encodes two digits in as
    much space as one letter.

    If maximum interchangeability with version 1 QR codes is desired (error
    correction level M), use exam IDs composed of only uppercase letters, and
    composed of at most 12 letters.

    Parameters
    ----------
    exam_token : str
        The identifier of the exam
    page_num : int
        The page number
    copy_num : int
        The number of the copy

    Returns
    -------
    Pillow Image object
        The Pillow image of the DataMatrix code, including quiet zone (you
        don't need to add a quiet zone yourself)
    """

    data = f'{exam_token}/{copy_num:04d}/{page_num:02d}'

    box_size = current_app.config['COPY_NUMBER_MATRIX_BOX_SIZE']

    encoded = encode(data.encode('utf-8'), size='18x18')
    datamatrix = PIL.Image.frombytes('RGB', (encoded.width, encoded.height),
                                     encoded.pixels)
    datamatrix = datamatrix.resize((box_size, box_size)).convert('L')
    return datamatrix
Beispiel #13
0
    def test_encode_module_size(self):
        data = b'hello world'
        encoded = encode(data, size='36x36', module_size=2)

        self.assertEqual(Encoded(width=92, height=92, bpp=24, pixels=None),
                         encoded._replace(pixels=None))
import shutil
from zipfile import ZipFile
from os import path
from shutil import make_archive

for dirpath, dirnames, files in os.walk('/var/www/html/files'):
    if files:
        directory = '/var/www/html/files/'
        files = os.listdir(directory)
        images = filter(lambda x: x.endswith('.csv'), files)
        i = 0
        with open('/var/www/html/files/' + str(images[0])) as f:
            reader = csv.reader(f, delimiter=' ')
            for row in reader:
                i += 1
                encoded = encode(str(row[0]))
                img = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels)
                img.save('/home/ivan/pylibdtmx/qrman/' + str(i) + '.png')

        os.remove('/var/www/html/files/' + str(images[0]))

        # ZIP_____________________________________________
        zip_name = '/home/ivan/pylibdtmx/qrman/'
        directory_name = '/home/ivan/pylibdtmx/qrman/'
        # Create 'path\to\zip_file.zip'
        shutil.make_archive(zip_name, 'zip', directory_name)

        # ZIP_____________________________________________OFF
        # sendingEmail____________________________________OFF
        f = open('/var/www/html/email.txt')
        emailTO = f.read()
Beispiel #15
0
 def __encode(self):
     return encode(self.text, size=self.size)
Beispiel #16
0
def textToDMTX(text,pixel = 600):
    dm = encode(text.encode(),size='12x12')
    o= np.frombuffer(dm.pixels, np.uint8).reshape(dm.width,dm.height,-1)
    return cv2.resize(o,(pixel,pixel),interpolation=cv2.INTER_NEAREST)
Beispiel #17
0
    def genMatrix(cls):
        encoded = encode(cls.key.encode('utf8'), scheme='Ascii', size='10x10')
        cls.img = Image.frombytes('RGB', (encoded.width, encoded.height),
                                  encoded.pixels)

        cls.img.save('../images/DMTX.png')
Beispiel #18
0
    def create_label(self,
                     part_no,
                     part_description,
                     barcode_data,
                     outfile,
                     debug=False):
        dm_code = encode(barcode_data, scheme="ascii")
        dm_image = Image.frombytes("RGB", (dm_code.width, dm_code.height),
                                   dm_code.pixels)

        if dm_image.height > (self.MIN_LABEL_HEIGHT - self.LABEL_MARGIN):
            self.LABEL_HEIGHT = dm_image.height + self.LABEL_MARGIN
        else:
            self.LABEL_HEIGHT = self.MIN_LABEL_HEIGHT

        image = Image.new(mode="L",
                          size=(self.LABEL_WIDTH, self.LABEL_HEIGHT),
                          color=255)

        if dm_image.height > image.height:
            print("Error")

        box_center_x = int(dm_code.width / 2 + self.LABEL_MARGIN)
        box_center_y = int(self.LABEL_HEIGHT / 2)

        text_start = int(box_center_x + dm_code.width / 2 + self.LABEL_MARGIN)
        text_end = image.width - self.LABEL_MARGIN
        text_max_width = text_end - text_start

        # Insert datamatrix code into image
        image.paste(
            dm_image,
            (
                int(box_center_x - dm_code.width / 2),
                int(box_center_y - dm_code.height / 2),
                int(box_center_x + dm_code.width / 2),
                int(box_center_y + dm_code.height / 2),
            ),
        )

        self.draw = ImageDraw.Draw(image)

        self.draw_text(
            part_no,
            text_start,
            text_end,
            self.LABEL_MARGIN,
            int((image.height - 2 * self.LABEL_MARGIN) / 3.0 +
                self.LABEL_MARGIN),
            self.font_name,
            align="right",
        )

        self.draw_text(
            part_description,
            text_start,
            text_end,
            int((image.height - 2 * self.LABEL_MARGIN) / 3.0 +
                self.LABEL_MARGIN),
            image.height - self.LABEL_MARGIN,
            self.font_name,
            align="right",
            multiline=True,
        )

        if debug:
            image.show()

        if outfile:
            image.save(outfile)
Beispiel #19
0
# From https://pypi.org/project/pylibdmtx/

from PIL import Image
import pylibdmtx.pylibdmtx as dmtx
import sys

#Get what to encode from the command line
id = sys.argv[1]
wh = int(sys.argv[2])

encoded = dmtx.encode(id.encode('utf8'))
img = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels)

#Resize to 400x400
im1 = img.resize((wh, wh), Image.NEAREST)

#Write image
im1.save('data/' + id + '.png')

#To test: http://boy.co.ua/decode.php