예제 #1
0
    def cmdcreatecode(self):
        QRText = self.qrtext.toPlainText()
        try:
            if self.qrbox.isChecked():
                if QRText != "":
                    QR = pyqrcode.create(QRText)
                    QR.png(savedcodes+QRText+'.png', scale=8)
                    image = QPixmap(savedcodes+QRText+".png")
                    qrscaled = image.scaled(261, 261, Qt.KeepAspectRatio)
                    self.qrcode.setPixmap(qrscaled)

            elif self.barbox.isChecked():
                if QRText != "":

                    barout = Code128(QRText, writer=ImageWriter())
                    barout.save(savedcodes+QRText+"-bar")
                    image = QPixmap(savedcodes+QRText+"-bar"+".png")
                    qrscaled = image.scaled(261, 261, Qt.KeepAspectRatio)
                    self.qrcode.setPixmap(qrscaled)
        
        except Exception:
            msgBox = QMessageBox()
            msgBox.setIcon(QMessageBox.Warning)
            msgBox.setWindowTitle("Code Generator")
            msgBox.setText("Error! code could not be created")
            msgBox.exec()
예제 #2
0
 def codebarImg(self, codebar):
     if (len(codebar) == 13):
         print("Predicted to have a EAN13 barcode")
         try:
             codebarImg = EAN13(codebar, writer=ImageWriter())
         except:
             ""
     elif (len(codebar) == 8):
         print("Predicted to have a EAN8 barcode")
         try:
             codebarImg = EAN8(codebar, writer=ImageWriter())
         except:
             ""
     elif (len(codebar) == 14):
         print("Predicted to have a EAN14 barcode")
         try:
             codebarImg = EAN14(codebar, writer=ImageWriter())
         except:
             ""
     else:
         print("Predicted to have a Code128 barcode")
         try:
             codebarImg = Code128(codebar, writer=ImageWriter())
         except:
             ""
     return codebarImg
def randomCode128() -> np.ndarray:
    number = ''.join(random.choice(string.digits + string.ascii_letters) for i in range(13))
    my_code = Code128(number, writer=ImageWriter())
    my_code.save("new_code", None, None)
    temp = cv2.imread("new_code.png")
    temp = temp[0:220, 0:480]
    return temp
예제 #4
0
def create_barcode(case_no,
                   code,
                   label_type='default',
                   file_path=BARCODE_FOLDER_ROOT_PATH):
    file_name = '{0}_{1}.{2}'.format(case_no, code, 'jpg')
    barcode_image_path = file_path.format(file_name)

    with open(file=barcode_image_path, mode='wb') as f:
        if code == 'code39':
            t = Code39(case_no, writer=ImageWriter(), add_checksum=False)
            t.write(f, options=writer_options[label_type])

        if code == 'code128':
            t = Code128(case_no, writer=ImageWriter())
            t.write(f, options=writer_options[label_type])

        if code == 'qr':
            qr = qrcode.QRCode(
                version=1,
                error_correction=qrcode.constants.ERROR_CORRECT_H,
                box_size=4,
                border=4,
            )
            qr.add_data(case_no)
            qr.make(fit=True)
            img = qr.make_image()
            img.save(barcode_image_path)
    return barcode_image_path
예제 #5
0
def barcoder(badSku):
    # Convert the SKU number into a string and strip the blankspace
    goodSku = str(badSku)
    itemNumber = goodSku.strip()
    # Create a filename for the barcode image, which will be the SKU number with a .png extension
    filename = "results/barcodes/" + itemNumber
    barcode = Code128(itemNumber, writer=ImageWriter())
    barcode.save(filename)
예제 #6
0
def textToC128(text, ):
    buf = BytesIO()
    c128 = Code128(text, writer=ImageWriter())
    c128.write(buf)
    buf.seek(0)
    filebyte = np.asarray(bytearray(buf.read()), dtype=np.uint8)
    res = cv2.imdecode(filebyte, cv2.IMREAD_GRAYSCALE)
    return np.r_[res[200:220, :], res[0:100, :], res[245:, :], res[200:210, :]]
예제 #7
0
def main():
    if len(sys.argv) >= 2:
        ns = str(sys.argv[1])
        # Generación del código de barras
        with open('imgs/barcode.png', 'wb') as f:
            Code128(ns, writer=ImageWriter()).write(f, options=BARCODE_OPTIONS)

        # Generación el pdf desde el template
        pdfkit.from_file('template.html', "etiquetas/" + ns + ".pdf", options=PDF_OPTIONS)
예제 #8
0
 def create_barcode_file(barcode_text):
     bc: Code128 = Code128(barcode_text, writer=ImageWriter())
     code_list: list = bc.build()
     code_size: int = len(code_list[0])
     options: dict = dict(font_size=config.font_size,
                          text_distance=config.text_distance,
                          module_width=config.code_width / code_size,
                          module_height=config.code_height,
                          quiet_zone=config.quiet_zone)
     return bc.save(f'{config.barcode_images_folder}/{barcode_text}',
                    options)
예제 #9
0
파일: bc.py 프로젝트: AyahnaSyahid/a3plus
def test1():
    code = Code128("Test_Code128").build()[0]
    size, mod = calculate_size( code, (320, 140) )
    print(size)
    canvas = Drawing(filename="My.svg", size=( 320, 140 ))
    barcode = canvas.add(canvas.g(id='barcode_g'))
    barcode.add(canvas.rect( (0, 0), size, fill='white'))
    bc_part = barcode.add(canvas.g(id='bc_part'))
    for i in mod:
        bc_part.add(canvas.rect(i[0], i[1], fill='black'))
    canvas.save(pretty=True)
예제 #10
0
 def returnn(self):
     joined = self.p0 + self.p90 + self.p45 + self.p45s + self.p135 + self.p135s
     #concatenates the list values into one string
     string = ''.join(map(str, joined))
     while len(string) != 70:
         string += str(0)
     path = ("MNIST_DS/" + str(self.a) + "/b_" + str(self.a) + str(self.b) +
             ".jpg")
     #outputs the string as a barcode
     with open(path, 'wb') as f:
         Code128(string, writer=ImageWriter()).write(f)
     return joined
예제 #11
0
파일: bot.py 프로젝트: ManuDeBuck/coaster
 def get_barcode(self, update, context):
     telegram_id = update.message.from_user.id
     client = self.clients.get_by_telegram_id(telegram_id)
     if client is not None:
         filename = "barcodes/{}.png".format(client.barcode)
         if not os.path.isfile(filename):
             code = Code128(client.barcode, writer=ImageWriter())
             code.save("barcodes/{}".format(client.barcode))
         context.bot.send_photo(
             chat_id=update.effective_chat.id,
             photo=open("barcodes/{}.png".format(client.barcode), "rb"))
     else:
         context.bot.send_message(chat_id=update.effective_chat.id,
                                  text="You currently are not a client.")
def print_info(document, categories=None):
    """Print report info page."""
    if categories is None:
        categories = {}
    if document["category"]:
        current_category = categories[document["category"]]
        cat_list = [current_category]

        while current_category["parent"]:
            cat_list.insert(0, categories[current_category["parent"]])
            current_category = categories[current_category["parent"]]
    else:
        cat_list = []

    printer.set(font="a", align="center")
    printer.text("DOCUMENTO - Archivetikett\n")
    printer.set(font="a", double_height=True, align="right", underline=False)
    printer.text("NR. {}\n".format(document["id"]))

    printer.set(font="b", align="left")
    printer.text("Titel:\n")
    printer.set(font="a", double_height=True, align="left", underline=True)
    printer.textln(document["name"])

    printer.set(font="b", align="left")
    printer.text("Zeitpunkt der Archivierung:\n")
    printer.set(font="a", double_height=False, align="left", underline=False)
    printer.textln(document["added_at"])

    printer.set(font="b", align="left")
    printer.text("Kategorie:\n")
    printer.set(font="a", double_height=False, align="center", underline=False)
    cat_names = ["[" + cat["name"] + "]\n" for cat in cat_list]
    printer.text("V\n".join(cat_names))

    printer.set(font="b", align="left")
    printer.text("Barcode:\n")
    barcode = document["barcode"]

    writer = ImageWriter()
    code = Code128(barcode, writer=writer).render({
        "module_width": 0.4,
        "module_height": 5.0,
        "text_distance": 3.0
    })
    printer.image(code, center=True)

    printer.ln(3)
    printer.control("LF")
예제 #13
0
파일: bc.py 프로젝트: AyahnaSyahid/a3plus
def test2(): 
    size = Size( 120 * 3.125, 55 * 3.125 ) # in 90dpi -> ' * 3.125 is for 300dpi 
    code = Code128("Holis_NHK").build()[0]
    modules = get_modules(code)
    Canv = Drawing(filename="Draw.svg", size = size.getS(float_precision=2))
    barcode = Canv.add(Canv.g(id="SomeID"))
    barcode.add(Canv.rect(('0','0'),size.getS(float_precision=2), fill='white'))
    xpos = int(size.getN[0] / 10)
    width = (size.getN[0] - ( size.getN[0] / 5)) / len(code)
    for ch, n in modules:
        pos = Size(xpos, 0)
        ms = Size(n * width, size.getN[1] * 7.5 / 10)
        if ch:
            barcode.add(Canv.rect((pos.getS()),(ms.getS()), fill="black"))
        xpos += ( n * width )
    barcode.add(Canv.text("Holis_NHK",x=["187.5px"], y=["162.5px"], style="fill:black;font-size:25pt;text-anchor:middle;"))
    Canv.save(pretty=True)
예제 #14
0
파일: bot.py 프로젝트: ManuDeBuck/coaster
 def get_item_barcode(self, update, context):
     command_split = update.message.text.split(" ")
     if len(command_split) < 2:
         context.bot.send_message(chat_id=update.effective_chat.id,
                                  text="Format: /get_item_barcode item")
         return
     item_name = command_split[1]
     item = self.items.get_by_item_name(item_name)
     if item is not None:
         filename = "barcodes/{}.png".format(item.barcode)
         if not os.path.isfile(filename):
             code = Code128(item.barcode, writer=ImageWriter())
             code.save("barcodes/{}".format(item.barcode))
         context.bot.send_photo(chat_id=update.effective_chat.id,
                                photo=open(
                                    "barcodes/{}.png".format(item.barcode),
                                    "rb"))
     else:
         context.bot.send_message(
             chat_id=update.effective_chat.id,
             text=f"The item with name {item_name} currently does not exist."
         )
예제 #15
0
# requeriments
#deve instalar o python-barcode
#pip install python-barcode[images]

from barcode import Code128
from barcode.writer import ImageWriter

#Gera o código de barras e salvar no caminho desejado
with open(r'test1.jpeg', 'wb') as f:
    Code128('210321000101', writer=ImageWriter()).write(f)


예제 #16
0
def QRCodeBarcodeGenerate():
    # Storing user-input text in a variable
    QrBarcodeString = QrBarcodeInput.get()
    # Storing the radio-button selection
    QrBarcodeSelection = radioVariable.get()

    # Checking the radio button selection and generating the codes as per the selection
    if QrBarcodeSelection == "qrcode":
        # Checking if the user has entered some text then do the following
        if QrBarcodeString != '':
            # Setting destination path to save the QRCode Image
            QRCodePath = '/Users/Ameer/Desktop/Новая папка (15)/Python-QRCodeBarcode-Generator-main'
            # Creating name with user-input text as the name and .png as the extension
            # Concatenating name with the path & qrcode keyword and storing in QRCodeName
            QRCodeName = QRCodePath + QrBarcodeString + ".png"

            # Generate object of QRCode with user-input text as the parameter
            qrGenerate = pyqrcode.create(QrBarcodeString)
            # Creating png image of QRCode using png(). To create png image pypng module
            # has to be installed. The png() takes the Filename & Scale Value as arguments
            qrGenerate.png(QRCodeName, scale=10)

            # Opening the saved QRCode Image using the open() method of the Image module
            image = Image.open(QRCodeName)
            # Resizing the image using Image.resize()
            image = image.resize((400, 400), Image.ANTIALIAS)
            # Creating object of PhotoImage() class to display the frame
            image = ImageTk.PhotoImage(image)
            # Configuring the label to displaying the QRCode Image
            root.imageLabel.config(image=image)
            root.imageLabel.photo = image
        # If the user has not entered any text then error is shown
        else:
            messagebox.showerror("Ошибка", "Введите Текст!")

    elif QrBarcodeSelection == "barcode":
        # Checking if the user has entered some text then do the following
        if QrBarcodeString != '':
            # Setting destination path to save the Barcode Image
            BarcodePath = '/Users/Ameer/Desktop/Новая папка (15)/Python-QRCodeBarcode-Generator-main'
            # Creating name for the image with user-input text as the name
            # Concatenating name with path & barcode keyword and storing in BarcodeName
            BarcodeName = BarcodePath + QrBarcodeString + "-barcode"

            # Creating an object of Code128 class with user-input string as the parameter
            # and passing the ImageWriter() as the value of writer argument.
            barcodeOutput = Code128(QrBarcodeString, writer=ImageWriter())
            # Saving the barcode using the save() method of the object of class EAN13
            # with QrBarcodeName as the argument. Automatically saves image in png format.
            barcodeOutput.save(BarcodeName)

            # Opening the saved Barcode Image using the open() method of the Image module
            image = Image.open(BarcodeName + ".png")
            # Resizing the image using Image.resize()
            image = image.resize((450, 300), Image.ANTIALIAS)
            # Creating object of PhotoImage() class to display the frame
            image = ImageTk.PhotoImage(image)
            # Configuring the label to displaying the Barcode Image
            root.imageLabel.config(image=image)
            root.imageLabel.photo = image
        # If the user has not entered any text then error is shown
        else:
            messagebox.showerror("ERROR", "ENTER A TEXT.!")
예제 #17
0
def generateCode128(dataString):
    code128Barcode = Code128(dataString, writer=ImageWriter())
    #TODO: Directly save barcode to variable instead of writing then reading
    pilImage = code128Barcode.render()
    return cv2.cvtColor(numpy.array(pilImage).astype(np.uint8), cv2.COLOR_RGB2BGR)
예제 #18
0
파일: main.py 프로젝트: emilbratt/OTGT
def generateBarcodes(values):

    print('\n\tGenererer strekkoder...\n')
    try:
        fontUsed = ImageFont.truetype('arial.ttf', 72)
    except OSError:
        fontUsed = ImageFont.truetype(os.path.join(path, 'FreeSans.ttf'), 72)

    for iterate, barValue in enumerate(values):

        fileName = os.path.join(path, 'Strekkoder', barValue)

        # convert value to barcode value
        Code128(barValue, writer=ImageWriter()).save(fileName)

        # open the barcode value as image and start
        openBarcode = Image.open('%s.png' % fileName).convert('L')

        if iterate % 19 == 0:
            if iterate % 38 == 0:
                # open an A4 size to pasted cropped versions
                A4sheet = Image.new('RGB', (1240, 1754),
                                    (255, 255, 255)).convert('L')
                saveA4sheet = str(int(iterate / 38)).zfill(
                    len(str(int(len(values) / 38))))
                pasteLeft = 50
            else:
                pasteLeft = 680

        pasteTop = (10 + (iterate % 19) * 92)

        # open new blank where cropped version of original will be pasted
        cropped = Image.new('RGB', (560, 80), (255, 255, 255))

        # Horizontal = openBarcode.size[0]
        # Vertical = openBarcode.size[1]
        cropValue = (0, 80, openBarcode.size[0], 160)
        # params:
        # start pixel left, start pixel top
        # end pixel right, end pixel bottom

        croppedRegion = openBarcode.crop(cropValue)
        cropped.paste(croppedRegion, (250, 0))
        # paste values represents: (pxiels from left, pixels from top)

        textInput = ImageDraw.Draw(cropped)
        textInput.text((0, 0),
                       barValue.rjust(7),
                       font=fontUsed,
                       fill=(0, 0, 0))

        A4sheet.paste(cropped, (pasteLeft, pasteTop))

        openBarcode.close()
        cropped.close()

        os.remove('%s.png' % fileName)

        if iterate % 38 == 37 or iterate == len(values) - 1:
            A4sheet.save('%s.png' %
                         os.path.join(path, 'Strekkoder', saveA4sheet))
            A4sheet.close()

        if sys.platform.startswith('linux') or sys.platform.startswith(
                'darwin'):
            loading_bar(iterate, len(values), barValue)
        elif sys.platform.startswith('win32'):
            print(fileName)

    openFolder(os.path.join(path, 'Strekkoder'))
예제 #19
0
파일: bar.py 프로젝트: 3mora2/barcode
def combine_vertically(l):
    # https://www.life2coding.com/combine-several-images-vertically-with-padding-using-opencv-python/
    images = []
    max_width = 0  # find the max width of all the images
    total_height = 0  # the total height of the images (vertical stacking)

    # for img in image:
    h = 3
    w = .23
    f = 15
    for text, ty in l:
        rv = BytesIO()
        option = {
            'module_width': w,
            'module_height': h,
            'quiet_zone': 6.5,
            'text_distance': 1,
            'font_size': f
        }
        h += 1
        # w = .22
        f = 17
        if len(text) > 10:
            text1 = text
        else:
            text1 = text.replace('', ' ').strip()
        Code128(text, writer=ImageWriter()).write(rv,
                                                  options=option,
                                                  text=text1)
        # Code39(text, writer=ImageWriter(), add_checksum=False).write(rv, options=option, text=text1)
        # generate('EAN13', text, writer=ImageWriter(), output=rv, writer_options=option)
        file_bytes = np.asarray(bytearray(rv.getvalue()), dtype=np.uint8)
        img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)[8:-15, :, :]
        # open all images and find their sizes
        images.append((img, ty))

        image_width = img.shape[1]
        image_height = img.shape[0]

        if image_width > max_width:
            max_width = image_width

        # add all the images heights
        total_height += image_height

    final_image = np.zeros((total_height + 200, max_width + 70, 3),
                           dtype=np.uint8)
    final_image.fill(255)

    current_y = 50  # keep track of where your current image was last placed in the y coordinate
    current_x = 55
    w = 30
    h = 30
    n = 1
    cv2.putText(final_image, ' Trevi', (200, 39), cv2.FONT_ITALIC, 1,
                (0, 0, 0), 2, cv2.LINE_AA)
    for image, txt in images:
        # add an image to the final array and increment the y coordinate
        height = image.shape[0]
        width = image.shape[1]
        final_image[current_y:height + current_y,
                    current_x:width + current_x, :] = image

        cv2.putText(final_image, txt, (w, current_y + h), cv2.FONT_ITALIC, 1,
                    (0, 0, 0), 2, cv2.LINE_AA)
        h = 40
        current_x = 100
        # current_x = 80
        if n == 2:
            w = 20
            # current_x = 80
        current_y += height
        n += 1
    t = 'Bluetooth Wireless In-Ear Earbuds With Charging Case White'.strip()
    if len(t) > 32:
        n1 = t.find(' ', 30)
        if n1 < 35:
            t1 = f'{t[:n1].strip()}'
            cv2.putText(final_image, t1, (w, current_y + h),
                        cv2.FONT_HERSHEY_SIMPLEX, .9, (0, 0, 0), 2,
                        cv2.LINE_AA)
            current_y = current_y + h
            t1 = f'{t[n1:].strip()}'
            cv2.putText(final_image, t1, (w, current_y + h),
                        cv2.FONT_HERSHEY_SIMPLEX, .9, (0, 0, 0), 2,
                        cv2.LINE_AA)

    return final_image
예제 #20
0
from barcode import Code128
from barcode.writer import ImageWriter
from PIL import Image
import os

number = 'HSDWJDWBDJWBJD'

code = Code128(number, writer=ImageWriter())

code.save('new')

im = Image.open(r'new.png')
im.save(r'new.jpg')

os.remove('new.png')
예제 #21
0
def barcode_to_base64(orderId):
    imgByteArray = io.BytesIO()
    Code128(str(orderId) + "\n", writer=ImageWriter()).write(imgByteArray)
    return base64.b64encode(imgByteArray.getvalue()).decode()