def generate(self, string, filename): file = os.path.join(os.path.dirname(__file__), "../barcodes", f"{filename}") # or sure, to an actual file: ean = barcode.get("Code128", f"{string}", writer=ImageWriter()) filename = ean.save(file, options={"write_text": False}) return filename
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, :]]
async def _(event): if event.fwd_from: return approved_userss = approved_users.find({}) for ch in approved_userss: iid = ch["id"] userss = ch["user"] if event.is_group: if await is_register_admin(event.input_chat, event.message.sender_id): pass elif event.chat_id == iid and event.sender_id == userss: pass else: return start = datetime.now() input_str = event.pattern_match.group(1) message = "SYNTAX: `.barcode <long text to include>`" reply_msg_id = event.message.id if input_str: message = input_str elif event.reply_to_msg_id: previous_message = await event.get_reply_message() reply_msg_id = previous_message.id if previous_message.media: downloaded_file_name = await event.client.download_media( previous_message, Config.TEMP_DOWNLOAD_DIRECTORY, ) m_list = None with open(downloaded_file_name, "rb") as fd: m_list = fd.readlines() message = "" for m in m_list: message += m.decode("UTF-8") + "\r\n" os.remove(downloaded_file_name) else: message = previous_message.message else: message = "SYNTAX: `/barcode <long text to include>`" bar_code_type = "code128" try: bar_code_mode_f = barcode.get(bar_code_type, message, writer=ImageWriter()) filename = bar_code_mode_f.save(bar_code_type) await event.client.send_file( event.chat_id, filename, caption=message, reply_to=reply_msg_id, ) os.remove(filename) except Exception as e: await event.reply(str(e)) return end = datetime.now() ms = (end - start).seconds await event.reply("Created BarCode in {} seconds".format(ms))
def createEan(self, title_txt, info_txt, ean_code, num): titleTxt = title_txt + "*" + num infoTxt = info_txt eanCode = ean_code self.imgCopyNum = int(num) or self.imgCopyNum imTitle = Image.open("resources/ean/imgTitleBg.png") imCopy = Image.open("resources/ean/imgCopyBg.png") draw1 = ImageDraw.Draw(imTitle) draw2 = ImageDraw.Draw(imCopy) # 设置本次使用的字体 #fontsFolder = 'C:\Windows\Fonts' # font1 = ImageFont.truetype(os.path.join(fontsFolder, 'Arial.TTF'), 420) font1 = ImageFont.truetype("C:/windows/fonts/simsun.ttc", 22) font2 = ImageFont.truetype("C:/windows/fonts/simsun.ttc", 15) # "simsun.ttc", 40) # 计算各文本的放置位置 #txtSize1 = draw1.textsize(titleTxt, font1) txtSize2 = draw2.textsize(infoTxt, font2) length = len(titleTxt) utf8_length = len(titleTxt.encode('utf-8')) #获取放入的文字编码后的长度 length = (utf8_length - length) / 2 + length #汉字是2个字节 英文和数字是单字节 draw1.text( ((imTitle.size[0] - length * 11) / 2, (imTitle.size[1] - 22) / 2), unicode(titleTxt, 'UTF-8'), fill=(0, 0, 0, 255), font=font1) draw2.text((imCopy.size[0] / 2 - txtSize2[0] / 2, imCopy.size[1] - 50), unicode(infoTxt, 'UTF-8'), fill=(0, 0, 0, 255), font=font2) ean = Code128(eanCode, writer=ImageWriter()) ean.save("tempEan") imgEan = Image.open("tempEan.png") imgEan.crop((0, 0, imgEan.size[0], imgEan.size[1])) imgEan = imgEan.resize((imCopy.size[0] - 26, 110)) imCopy.paste(imgEan, ((imCopy.size[0] - imgEan.size[0]) / 2, 15)) # 绘制线框 #draw.line([(20, 20), (980, 20), (980, 1780), (20, 1780), (20, 20)], fill=(217, 217, 217, 255), width=5) showNum = self.imgCopyNum + 1 resultImg = Image.new('RGB', (imCopy.size[0], showNum * imCopy.size[1]), (0, 0, 0)) imTitleOrigin = imTitle.crop((0, 0, imCopy.size[0], imCopy.size[1])) resultImg.paste(imTitleOrigin) for i in range(showNum): region = imCopy.crop((0, 0, imCopy.size[0], imCopy.size[1])) resultImg.paste(region, (0, (i + 1) * imCopy.size[1])) resultImg.show() if (os.path.exists("tempEan.png")): os.remove("tempEan.png")
def save(self, *args, **kwargs): x = nomor() EAN = barcode.get_barcode_class('ean13') ean = EAN(f'{x}', writer=ImageWriter()) buffer = BytesIO() ean.write(buffer) self.barcode.save(f'{self.name}.png', File(buffer), save=False) self.barcodenum = x return super().save(*args, **kwargs)
def genera_bardcode(self,br): options = {} options["write_text"] = False options["text"] = '' generated = barcode.codex.Code39(br, writer=ImageWriter(), add_checksum=False) generated.render(options) print options filename = generated.save(str(br)) return filename
def generate(tax_id, nat_id, verification_code, amount, filename): amount = str(int(amount)) + '00' writer = ImageWriter() writer.hello = types.MethodType(paint_text, writer) writer.register_callback('paint_text', writer.hello) barcode_str = ('|' + tax_id + '\x0d' + nat_id + '\x0d' + verification_code + '\x0d' + amount) c = barcode.get('code128', barcode_str, writer) c.save(filename)
def createbar_code39(code): EAN = barcode.get_barcode_class('code39') ean = EAN(code, writer=ImageWriter()) fullname = ean.save(code) fp = StringIO() ean.write(fp) return fullname
def generate(input_tuple, filename): elements = list(input_tuple) data_to_encode = "-".join(elements) data_to_encode = data_to_encode.replace('_', '-') print('Generating barcode for', data_to_encode) print('Saving to', filename) with open(filename, 'wb') as fh: Code39(data_to_encode, writer=ImageWriter()).write(fh)
def EditItem(request, item_id): data = { 'name': Item.objects.get(pk=item_id), 'category': Item.objects.get(pk=item_id).category, 'design': Item.objects.get(pk=item_id).design, 'shade': Item.objects.get(pk=item_id).shade, 'unit': Item.objects.get(pk=item_id).unit, 'unit_size': Item.objects.get(pk=item_id).unit_size, 'product_type': Item.objects.get(pk=item_id).product_type, 'manufacturer': Item.objects.get(pk=item_id).manufacturer, 'sale_rate': Item.objects.get(pk=item_id).sale_rate, 'barcode': Item.objects.get(pk=item_id).barcode, 'discount': Item.objects.get(pk=item_id).discount, 'image': Item.objects.get(pk=item_id).image, 'status': Item.objects.get(pk=item_id).status, 'deal': Item.objects.get(pk=item_id).deal, } if request.method == 'POST': item = Item.objects.get(pk=item_id) item.name = request.POST['name'] item.category = Category.objects.get(pk=request.POST['category']) item.design = Design.objects.get(pk=request.POST['design']) if request.POST['shade'] == '': item.shade = None else: item.shade = Shade.objects.get(pk=request.POST['shade']) item.unit = Unit.objects.get(pk=request.POST['unit']) item.unit_size = request.POST['unit_size'] item.product_type = request.POST['product_type'] item.manufacturer = Manufacturer.objects.get(pk=request.POST['manufacturer']) item.sale_rate = request.POST['sale_rate'] item.barcode = request.POST['barcode'] if request.POST['discount'] == '': item.discount = None else: item.discount = request.POST['discount'] try: item.image = request.FILES['image'] except: try: if request.POST['image-clear']: item.image = None except: item.image = item.image item.status = request.POST['status'] item.deal = request.POST['deal'] item.barcode_img.delete() ean = EAN(request.POST['barcode'], writer=ImageWriter()) item.barcode_img = ean.save(request.POST['name']) f = request.POST['name'] + '.png' os.chdir(settings.BASE_DIR) shutil.move(f, settings.MEDIA_ROOT) item.save() return redirect('master:item') else: form = ItemForm(initial=data, user=request.user) return render(request, 'master/pages/add-item.html', {'form': form})
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)
def generateBarcodes(products, parent_dir, directory1, directory2): for i in products: # create an object of Code39 class and # pass the number with the ImageWriter() as the writer my_code = Code39(i.info, writer=ImageWriter(), add_checksum=False) # Our barcode is ready. Let's save it. image = my_code.save( parent_dir + "/" + directory1 + "/" + "code%s_" % (i.refnum) + i.info, { "module_width": 0.15, "module_height": 12, "font_size": 10, "text_distance": 1.5, #"font_path": 'Arial.ttf', "quiet_zone": 3 }) # create a white canvas canvasWidth, canvasHeight = 600, 400 canvas = Image.new('RGB', (canvasWidth, canvasHeight), 'white') draw = ImageDraw.Draw(canvas) # set font font1 = ImageFont.truetype("arial.ttf", 28) font2 = ImageFont.truetype("arial.ttf", 15) # draw texts draw.text((45, 45), "PART NUMBER", font=font1, fill='black') draw.text((445, 45), "QTY", font=font1, fill='black') draw.text((45, 100), i.partName, font=font1, fill='black') draw.text((445, 100), i.quantity, font=font1, fill='black') # open barcode image im1 = Image.open( os.path.expanduser(parent_dir + "/" + directory1 + "/" + "code%s_" % (i.refnum) + i.info + ".png")) width, height = im1.size pastePos = ((canvasWidth - width) // 2, 165) if width > canvasWidth - 20: #resize to fit in centre newSize = (canvasWidth - 20, 203) im1 = im1.resize(newSize) pastePos = (10, 165) # copy the barcode image to canvas canvas.paste(im1, pastePos) # add refnum to left-corner draw.text((30, 350), str(i.refnum), font=font2, fill='black') #save images canvas.save(parent_dir + "/" + directory2 + "/" + "im%s_" % (i.refnum) + i.info + ".pdf")
def generate_barcode_binary(data): ean = barcode.get('ean13', data, writer=ImageWriter()) img = ean.render() tmp = tempfile.mktemp() img.save(tmp, 'GIF') with open(tmp, 'rb') as f: binary = f.read() os.remove(tmp) return binary
def testEan(): imagewriter = ImageWriter() # 保存到图片中 # add_checksum : Boolean Add the checksum to code or not (default: True) ean = Code39("1234567890", writer=imagewriter, add_checksum=False) # 不需要写后缀,ImageWriter初始化方法中默认self.format = 'PNG' ean.save('image') img = Image.open('image.png') img.show()
def generate_barcode(block): import barcode from barcode.writer import ImageWriter code39 = barcode.get_barcode_class('code39') barcode39 = code39(str(block.getHash()), writer=ImageWriter()) # fileName = pathTicket + '\\barcode'+str(block.getIndex()) fileName = os.path.join(pathTicket, 'barcode'+str(block.getIndex())) barcode39.save(fileName)
def generate_barcode(number): barcode_image = barcode.get("code128", str(number), writer=ImageWriter()) opts = dict(write_text=True, module_width=.4, module_height=5, text_distance=1.5, font_size=12, quiet_zone=2) return barcode_image.render(opts)
def get_barcode_128(self): if self.claveacceso: file_data = StringIO.StringIO() generate('code128', u'{}'.format(self.claveacceso), writer=ImageWriter(), output=file_data) file_data.seek(0) self.barcode128 = base64.encodestring(file_data.read())
def createC39(lab_number): d = path.dirname(__file__) parent_path = os.path.dirname(d) parent_path = parent_path.replace("\\", "/") imagewriter = ImageWriter() # add_checksum : Boolean Add the checksum to code or not (default: True) ean = Code39(lab_number, writer=imagewriter, add_checksum=False) # 不需要写后缀,ImageWriter初始化方法中默认self.format = 'PNG' ean.save(parent_path + '/static/scan/c39/' + lab_number)
def get_br(bno): import barcode #msgprint("bno "+cstr(bno)) from barcode.writer import ImageWriter EAN = barcode.get_barcode_class('code39') ean = EAN(bno, writer=ImageWriter()) fullname = ean.save(bno) #msgprint("from utils "+cstr(fullname)) return fullname
def make_barcode_png(data, **options): barcodefile = io.BytesIO() code128 = barcode.get('code128', data, writer=ImageWriter()) # Sizes here are the ones used in the PDF code128.write(barcodefile, {'write_text': False, 'module_height': 8}) barcodefile.seek(0) return barcodefile
def barcode_img_gen(barcode_value): """ Generates the barcode image :param barcode_value: the string of the barcode value :return: the newly created barcode image """ code_39 = barcode.get_barcode_class('code39') return code_39(barcode_value, writer=ImageWriter(), add_checksum=False)
def bar_generator(digits=123456789123): # digits=123456789123 is a default value, if no other values is passed. # io.BytesIO makes sure you only save to memory instead of disk. rv = io.BytesIO() EAN13(str(digits), writer=ImageWriter()).write(rv) image = Image.open(rv) # Resize and display the BAR code image = image.resize((400, 400), Image.ANTIALIAS) image.show()
def generateSticker(model, size, gtin, serial, dmC): lim = 1.2 w = round(dmC.width * lim) h = round(dmC.height * lim) print("%s %s %s %s" % (model, size, gtin, serial)) # os.system( 'zint --height 20 -o ean.png -b 13 -d "%s"'%( gtin[5:17] ) ) print(gtin) print(gtin[5:18]) with open('ean.png', 'wb') as f: EAN13('%s' % (gtin[5:18]), writer=ImageWriter()).write(f) dmCode = dmC dmCode = dmCode.resize((w, h)) img = Image.open("./maket.png") img.paste(dmCode, box=(600, 70)) ean = Image.open("./ean.png") ean = ean.crop((60, 1, 500, 150)) img.paste(ean, box=(95, 645)) w = round(len(model) * 30 / 2) print(w) txt = Image.new("RGBA", img.size, (255, 255, 255, 0)) fnt = ImageFont.truetype("Pillow/Tests/fonts/FreeMonoBold.ttf", 90) fnt1 = ImageFont.truetype("Pillow/Tests/fonts/FreeMonoBold.ttf", 45) # get a drawing context d = ImageDraw.Draw(txt) # draw text, half opacity d.text((100, 130), model, font=fnt, fill=(0, 0, 0, 255)) # draw text, full opacity d.text((230, 330), size, font=fnt, fill=(0, 0, 0, 255)) d.text((550, 570), gtin, font=fnt1, fill=(0, 0, 0, 255)) d.text((650, 670), serial, font=fnt1, fill=(0, 0, 0, 255)) img = Image.alpha_composite(img, txt) # draw.font_size = 110 # draw.text( 320 - w, 240, model ) # draw.text( 250, 420, size ) # draw.font_size = 70 # draw.font_size = 50 # draw.text( 580, 630, gtin ) # draw.text( 680, 720, serial ) # # draw( img ) now = datetime.datetime.now() name = "./images_ns/m%s_s%s_%s_%s_%s_%s_%s_%s_%s.png" % ( model, size, now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond) print(name) img.save(name) dmCode.save("dout_ns.png")
def add_barcode(document, page_num): # print(barcode.PROVIDED_BARCODES) ITF = barcode.get_barcode_class('itf') itf = ITF('{}'.format(page_num), writer=ImageWriter()) itf_path = r'C:\Users\j20687\Desktop\itf{}_barcode'.format(page_num) itf.save(itf_path) p = document.add_paragraph() p.alignment = WD_ALIGN_PARAGRAPH.RIGHT run = p.add_run() run.add_picture(itf_path + '.png', height=Cm(0.5), width=Cm(4))
def get_barcode(self, instance): ean = Code39(u''+str(instance.id), writer=ImageWriter()) ean.default_writer_options.update(font_size=20) barcode_img = tempfile.mktemp(suffix='.png') localFile = open(barcode_img, 'w') ean.write(localFile) localFile.close() img = open(barcode_img, 'r') img_str = img.read() return "data:image/png;base64,{}".format(b64encode(img_str))
def createBarCode(): hr = barcode.get_barcode_class("code39") while True: userInput = input("Enter the test your want to encode. ") if(len(userInput) > 0): break else: print("Enter an valid string") Hr = hr(userInput, writer=ImageWriter()) br = Hr.save("barcode")
def create(type, num): """ Parametr num should be a string type :param type: str :param num: str :return: None """ EAN = barcode.get_barcode_class(type) ean = EAN(u'{}'.format(num), writer=ImageWriter()) ean.save('created_barcode')
def get_barcode(rid): if not os.path.exists(qrimage_dir): os.mkdir(qrimage_dir) EAN = barcode.get_barcode_class('code128') ean = EAN(u'{}{:05}'.format(YEAR, int(rid)), writer=ImageWriter()) imgname = ean.save('{}/{}'.format(qrimage_dir, rid)) fp = open('{}'.format(imgname), 'wb') ean.write(fp) fp.close()
def generate_barcode(string, output_extension): if output_extension in ('PNG', 'png'): ean = barcode.get('Code39', string, writer=ImageWriter()) else: ean = barcode.get('Code39', string, writer=None) ean.default_writer_options['module_height'] = 13.0 ean.default_writer_options['module_width'] = 0.01 filename = ean.save(string) return filename
def make_barcode(code, acft): leading = '000' if acft == 'luh': leading = '720' elif acft == 'apache': leading = '640' code = leading + str(code) ean = barcode.get('ean13', code, writer=ImageWriter()) filename = ean.save('barcodes/{}'.format(code)) return filename