Пример #1
0
    def test_charset_encoding(self):
        """Make sure the character set encoding, code type switching
        and optimization works correctly"""
        known_good = {
            # dense C encoding
            # immediate switch into C-mode, should compress
            "1234": [105, 12, 34],

            # B only
            "hello": [104, 72, 69, 76, 76, 79],

            # B switching to C
            "HI345678": [104, 40, 41, 99, 34, 56, 78],
            "BarCode 1": [104, 34, 65, 82, 35, 79, 68, 69, 0, 17],
        }
        for text, encoded in known_good.items():
            enc = Code128Encoder(text)
            self.assertEqual(enc.encoded_text, encoded)

        # B => C => B, with leftover digit
        self.assertEqual(
            Code128Encoder('HI34567A').encoded_text,
            [104, 40, 41, 99, 34, 56, 100, 23, 33])

        # there was a Bug in C encoding when we have a leftover digit at the end
        # see https://github.com/hudora/huBarcode/issues/issue/11
        self.assertEqual(
            Code128Encoder('12345').encoded_text, [105, 12, 34, 100, 21])
Пример #2
0
def excelCode128(file, bar_width, bar_height, bar_fontSize, bar_margin):
    '''
    批量生成条码
    file(test.xlsx)   excel A列 商品编码 文件名。
    file1(pic.xlsx)   excel A列生成的条形码。
    '''
    wb = load_workbook(file)
    sheet = wb.active

    file1 = BAR_CODE_PATH + 'pic.xlsx'
    if os.path.exists(file1):
        os.remove(file1)
    shutil.copyfile(BAR_CODE_PATH + 'start.xlsx', file1)
    wb1 = load_workbook(file1)
    sheet1 = wb1.active
    f = []
    for r in range(1, sheet.max_row + 1):
        # A列数据生成条码
        var = sheet.cell(column=1, row=r).value
        filename = str(var) + '.png'
        #ttf_fontsize:字号、label_border:行距(条码与字之间的距离)、bottom_border:字与下边框之间的距离、height:矩形框高度、bar_width:矩形框宽度
        encoder = Code128Encoder(str(var),\
            options={"ttf_fontsize":bar_fontSize,"bottom_border":5,\
                     "height":bar_height, "label_border":bar_margin})
        encoder.save(filename, bar_width=bar_width)
        #Code128Encoder(str(var)).save(filename,bar_width=1
        # 另一个表 A列数据插入条码
        img = Image(filename)
        A = 'A' + str(r)
        sheet1.add_image(img, A)
        f.append(filename)
    wb1.save(file1)
    [os.remove(filename) for filename in f]
    print("批量生成条码成功!共计%s条!" % str(len(f)))
Пример #3
0
    def test_check_sum(self):
        """Make sure the checksum is calculated correctly"""

        known_good = {"HI345678": 68, "BarCode 1": 33}

        for text, chk in known_good.items():
            enc = Code128Encoder(text)
            self.assertEqual(enc.checksum, chk)
Пример #4
0
def code128(payload):
    if args.verbose:
        logging.getLogger("code128").setLevel(logging.DEBUG)
        logging.getLogger("code128").addHandler(
            logging.StreamHandler(sys.stdout))

    encoded = Code128Encoder(payload)
    encoded.save(args.outfile)
Пример #5
0
    def push_Code128_click(self):
        data = self.text_code128.toPlainText()
        if data:
            encoder = Code128Encoder(data)
            encoder.save("code128.png")

            code128 = QtGui.QPixmap('code128.png')
            self.label_show_Code128.setPixmap(code128)
Пример #6
0
 def create_Code128_img(self, barcode):
     a = Code128Encoder(barcode, options={
         'ttf_font': r'E:\web\TY_RMS_Multiple_Manage\static\fonts\arial.ttf',
         'label_border': 0, 'height': 92,  'bottom_border': 0,
     })
     # bar_width 条码宽度尺寸
     file_name = str(uuid.uuid4()) + '.png'
     a.save(file_name, bar_width=2)
     self.printer_code(file_name)
Пример #7
0
    def test_bar_encoding(self):
        """Make sure the bar encoding works correctly"""
        bars = "11010010000" + "11000101000" + "11000100010" + \
            "10111011110" + "10001011000" + "11100010110" + \
            "11000010100" + "10000100110" + "11000111010" + "11"

        text = "HI345678"

        enc = Code128Encoder(text)
        self.assertEqual(enc.bars, bars)
 def create_barcode(self, id):
     foo = Code128Encoder(id)
     print(foo.get_imagedata())
     img_path = "E:\Odoo 12.0\server\my-modules\itsm_device\static\image" + id + '.png'
     if os.path.exists(img_path):
         os.remove(img_path)
         foo.save(img_path)
     # 保存图片,返回图片路径
     else:
         foo.save(img_path)
     return img_path
Пример #9
0
    def test_against_generated(self):
        """Compare the output of this library with generated barcodes"""

        for index, string in enumerate(Code128Test.test_strings):
            generated = tempfile.mkstemp(".png")[1]
            encoder = Code128Encoder(string)
            encoder.save(generated)

            test_against = 'pystrich/code128/test_img/%d.png' % (index + 1)
            self.assertTrue(filecmp.cmp(generated, test_against),
                            msg="{} didn't match {}".format(
                                test_against, generated))
Пример #10
0
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        # generate the barcode PNG image.
        barcode = self.barcode
        img_path = os.path.join(MEDIA_ROOT, "products/{}.png".format(barcode))
        encoder = Code128Encoder(barcode, options=BARCODE_IMAGE_OPTIONS)
        encoder.save(img_path)
        self.barcode_img = "products/{}.png".format(barcode)

        return super().save(force_insert=force_insert,
                            force_update=force_update, using=using,
                            update_fields=update_fields)
    def create(self, vals):
        # 创建配置项产品自动生成设备二维码
        # 定义二维码所包含的信息

        # data = {'name': vals['name'],
        #         'ip': vals['ip']}
        # 调用函数生成二维码图片,返回图片路径
        vals['number'] = self.create_number()
        # img_path = self.create_barcode(vals['number'])
        foo = Code128Encoder(vals['number']).get_imagedata()
        img_qr = base64.b64encode(foo)
        vals['qr_img'] = img_qr
        result = super().create(vals)
        return result
Пример #12
0
def genBarCode(msg):
    options = {
        'height': 120,  # 条形码的高度
        'label_border': 10,  # 标签和二维码之间的距离
    }
    encoder = Code128Encoder(msg, options=options)
    encoder.save('barCode/' + msg + '.png')

    # 对条形码进行裁剪
    img = cv2.imread('barCode/' + msg + '.png')
    cropped = img[2:105, 0:460]
    cv2.imwrite('barCode/' + msg + '.png', cropped)

    # 对条形码进行缩放,缩放到558宽度
    reSizeImg('barCode/' + msg + '.png', width=558)

    return 'barCode/' + msg + '.png'
Пример #13
0
def en_coder(r, f, sheet1, bar_width, bar_height, bar_fontSize, bar_margin):
    '''
    数据生成条码
    ttf_fontsize:字号、label_border:行距(条码与字之间的距离)、bottom_border:字与下边框之间的距离、
    height:矩形框高度、bar_width:矩形框宽度
    '''
    filename = '%s.png' % (r)
    encoder = Code128Encoder(r,options={"ttf_fontsize":bar_fontSize,\
        "bottom_border":5,"height":bar_height, "label_border":bar_margin})
    encoder.save(filename, bar_width=bar_width)

    # 电子表格 A列数据插入条码
    img = Image(filename)
    f.append(filename)
    x = len(f)
    A = 'A' + str(x)
    sheet1.add_image(img, A)
    return f
Пример #14
0
def get_barcode_image(code, codetype='ean13'):
    from PIL import Image
    from io import BytesIO
    from pystrich.code128 import Code128Encoder
    from pystrich.ean13 import EAN13Encoder
    from pystrich.code39 import Code39Encoder
    codermap = {
        'code128': lambda code: Code128Encoder(code, options={'height': 100}),
        'ean13': lambda code: EAN13Encoder(code),
        'code39': lambda code: Code39Encoder(code, options={'height': 100}),
    }
    codetype = codetype.lower()
    if codetype not in codermap:
        import warnings
        warnings.warn('unsupported barcode type "%s"' % (codetype))
    else:
        encoder = codermap[codetype](code)
        img = Image.open(BytesIO(encoder.get_imagedata(4)))
        return img
Пример #15
0
    def label_show_detection(self):
        ret, frame = self.cap.read()
        self.timer_camera.stop()
        show_1 = cv2.resize(frame, (640, 480))
        cv2.imwrite('show.jpg', show_1)
        # show_1 = cv2.cvtColor(show_1, cv2.COLOR_BGR2RGB)


        # 识别文字
        cut_image = show_1[self.left_top[1] + self.top_cut:self.right_bottom[1] - self.bottom_cut, self.left_top[0] + self.left_cut:self.right_bottom[0] - self.rigth_cut]
        cut_image  = cv2.cvtColor(cut_image, cv2.COLOR_BGR2GRAY)
        cv2.imwrite('cut_img.png', cut_image)

        equ = cv2.equalizeHist(cut_image)

        cv2.imwrite('cut_img1.png', equ)
        # cccc = cv2.imread('cut_img.jpg')
        # cutImage = QtGui.QImage(cccc.data, cccc.shape[1], cccc.shape[0], QtGui.QImage.Format_RGB888)
        # self.label_show_result.setPixmap(QtGui.QPixmap.fromImage(cutImage))
        #
        cutImage = QtGui.QPixmap('cut_img.png')
        self.label_show_result.setPixmap(cutImage)


        words_str = self.read_word('cut_img.png')

        # words_str = 'MC20180601054'
        if words_str:
            self.text_code128.setText(words_str)
            encoder = Code128Encoder(words_str)
            encoder.save("code128.png")

            # code128 = cv2.imread("code128.png")
            # code128 = cv2.resize(code128, (420, 150))
            # Coderimage = QtGui.QImage(code128.data, code128.shape[1], code128.shape[0], QtGui.QImage.Format_RGB888)
            # self.label_show_Code128.setPixmap(QtGui.QPixmap.fromImage(Coderimage))

            code128 = QtGui.QPixmap('code128.png')
            self.label_show_Code128.setPixmap(code128)
        else :
            self.text_code128.setText('请手动输入')
            self.label_show_result.clear()
Пример #16
0
    def gen_codes(self):
        global im,imtk,font
        
        self.progressbar["value"] = 0
        if self.code_listbox.size() > 0:
            step = 100/self.code_listbox.size()
        for index in range(self.code_listbox.size()):
            ## RFID转换为CODE128
            line = self.code_listbox.get(index)
            byte_line = bytes.fromhex(line)
            value = self.conv(byte_line).decode()

            ## 生成CODE128图片
            im_height = int(self.setting_height_entry.get())
            encoder=Code128Encoder(value,{'bottom_border':80,'height':im_height})
            filedir = self.export_files_entry.get()
            
            if os.path.exists(filedir) == False:
                os.makedirs(filedir)
                
            filename = filedir+"/{}.png".format(line)
            encoder.save(filename,bar_width=4)
            
            ## 图片中写入RFID值
            im = Image.open(filename)
            width,height=im.size
            draw = ImageDraw.Draw(im)
            draw.text((20,height-100),line,font=font)
            im.save(filename)

            ## 显示缩略图
            canvas_width = int(self.preview_canvas['width'])
            canvas_height = int(self.preview_canvas['height'])
            im.thumbnail((canvas_width,canvas_height))
            imtk = ImageTk.PhotoImage(im)
            self.preview_canvas.create_image(canvas_width/2,canvas_height/2,image=imtk)

            ## 进度条显示
            self.progressbar["value"] += step
            self.root.update()
Пример #17
0
from pystrich.ean13 import EAN13Encoder
from pystrich.code128 import Code128Encoder
from io import BytesIO
from PIL import Image

if __name__ == '__main__':
    # encoder = EAN13Encoder("690123456789")
    encoder = Code128Encoder("690123456789")  #不同编码区别?
    #保存图片,并打开后print
    encoder.save("pyStrich.png")
    im = Image.open('pyStrich.png')
    im.show()

    #直接print
    fp = BytesIO()
    fp.write(encoder.get_imagedata())
    tmp = Image.open(fp)
    tmp.show()
Пример #18
0
def create_barcode(code):
    # code=random.randint(1000000000,999999999)
    path='barcode/'+str(code)+'.jpg'
    encoder=Code128Encoder(str(code))
    encoder.save(path)
Пример #19
0
"""Generate test images for code128 barcode encoder"""
from pystrich.code128 import Code128Encoder
from pystrich.code128.test_code128 import Code128Test

for index, string in enumerate(Code128Test.test_strings):
    enc = Code128Encoder(string)
    enc.save("pystrich/code128/test_img/%d.png" % (index + 1))
Пример #20
0
"""Example code for code128 library"""

import logging
import sys
from pystrich.code128 import Code128Encoder

logging.getLogger("code128").setLevel(logging.DEBUG)
logging.getLogger("code128").addHandler(logging.StreamHandler(sys.stdout))

if __name__ == "__main__":
    encoder = Code128Encoder(sys.argv[1])
    encoder.save("test.png")
Пример #21
0
 def encoder(self, barcode):
     code = Code128Encoder(barcode)
     code.save(os.path.join(self.path, barcode + ".png"))
Пример #22
0
# Código de Rastreamento --------------- 13
# Serviços Adicionais (AR, MP, DD, VD) - 8
# Cartão de Postagem ------------------- 10
# Código do Serviço -------------------- 5
# Informação de Agrupamento ------------ 2
# Número do Logradouro ----------------- 5
# Complemento do Logradouro ------------ 20
# Valor Declarado ---------------------- 5
# DDD + Telefone Destinatário ---------- 12
# Latitude ----------------------------- 10
# Longitude ---------------------------- 10
# Pipe "|" ----------------------------- 1
# Reserva para cliente ----------------- 30
encoder_dm = DataMatrixEncoder(
    '12221150000001620312500000651OO382192458BR0000000000000075022907041621I0000000000000000000000000000000000000|'
)
encoder_dm.save('matrix.png')

# codigo de rastreio
cod_rastreio = Code128Encoder('OO382192458BR')
cod_rastreio.save('cod_rastreio.png')

# cep de destino
cep_destino = Code128Encoder('12221150')
cep_destino.save('cep_destino.png')

# converte html em pdf
pdfkit.from_file('etiqueta.html', 'etiqueta.pdf')

# imprime etiqueta
os.startfile('etiqueta.pdf', 'print')
Пример #23
0
def gen_barcode(code='123456'):
    ## 生成二维码
    f = io.BytesIO()
    Code128Encoder(code).save(f)
    return f
Пример #24
0
import re
PUBLIC_SIZE = 24
typename = input('请输入款式')
size = input("请输入型号")
color = input("请输入颜色对照码")
typesize = '%s%s%s' % (typename, size, color)
with open('number.txt', 'r+') as f:
    data = f.read()
    if typesize in data:
        number = re.search(r'%s(\w+)' % typesize, data).group(1)
        NUMBER = int(number) + PUBLIC_SIZE
        data = re.sub(r'%s(\w+)' % typesize, '%s%d' % (typesize, NUMBER), data)
        f.write(data)
    else:
        print('+++')
        data += '%s%d\n' % (typesize, PUBLIC_SIZE)
        number = '0'
        NUMBER = int(number) + PUBLIC_SIZE
with open('number.txt', 'w+') as f:
    f.write(data)
img_list = []
for i in range(int(number), NUMBER):
    i = str(i).zfill(6)
    encoder = Code128Encoder("%s%s" % (typesize, i))
    img_list.append(BytesIO(encoder.get_imagedata()))
toImage = Image.new('RGBA', (1550, 2000))
for i in range(PUBLIC_SIZE):
    fromImge = Image.open(img_list[i])
    loc = ((int(i / 8) * 520), (i % 8) * 200)
    toImage.paste(fromImge, loc)
toImage.save('merged.png', quality=100)