本文整理汇总了Python中qrtools.QR.encode方法的典型用法代码示例。如果您正苦于以下问题:Python QR.encode方法的具体用法?Python QR.encode怎么用?Python QR.encode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类qrtools.QR
的用法示例。
在下文中一共展示了QR.encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
def generate(codes = range(20), width=2.0, cols = 5):
width_str = '%fcm' % width
tex_figs = ''
c_strs = []
f_strs = []
for c in codes:
c_str = '%06d' % c
qr = QR(data = url_fmt % c)
img_filename = img_dir + '/%s.png' % c_str
qr.encode(img_filename)
c_strs.append(c_str)
f_strs.append(figure_fmt % (width_str, img_filename))
elts = []
for i in range(0,len(codes),cols):
elts.append(c_strs[i:i+cols])
elts.append(f_strs[i:i+cols])
tex_file = open(tex_filename, 'w')
tex_file.write(tex_fmt % list_to_table(elts))
tex_file.close()
subprocess.check_call(['pdflatex',tex_filename],cwd=tex_dir)
示例2: qrencode
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
def qrencode(self, fileName=None):
#Functions to get the correct data
data_fields = {
"text": unicode(self.textEdit.toPlainText()),
"url": unicode(self.urlEdit.text()),
"bookmark": ( unicode(self.bookmarkTitleEdit.text()), unicode(self.bookmarkUrlEdit.text()) ),
"email": unicode(self.emailEdit.text()),
"emailmessage": ( unicode(self.emailEdit.text()), unicode(self.emailSubjectEdit.text()), unicode(self.emailBodyEdit.toPlainText()) ),
"telephone": unicode(self.telephoneEdit.text()),
"phonebook": (('N',unicode(self.phonebookNameEdit.text())),
('TEL', unicode(self.phonebookTelEdit.text())),
('EMAIL',unicode(self.phonebookEMailEdit.text())),
('NOTE', unicode(self.phonebookNoteEdit.text())),
('BDAY', unicode(self.phonebookBirthdayEdit.date().toString("yyyyMMdd")) if self.phonebookBirthdayLabel.isChecked() else ""), #YYYYMMDD
('ADR', unicode(self.phonebookAddressEdit.text())), #The fields divided by commas (,) denote PO box, room number, house number, city, prefecture, zip code and country, in order.
('URL', unicode(self.phonebookUrlEdit.text())),
# ('NICKNAME', ''),
),
"sms": ( unicode(self.smsNumberEdit.text()), unicode(self.smsBodyEdit.toPlainText()) ),
"mms": ( unicode(self.mmsNumberEdit.text()), unicode(self.mmsBodyEdit.toPlainText()) ),
"geo": ( unicode(self.geoLatEdit.text()), unicode(self.geoLongEdit.text()) ),
"wifi": ( unicode(self.wifiSSIDEdit.text()), (u"WEP",u"WPA",u"nopass")[self.wifiEncriptionType.currentIndex()], unicode(self.wifiPasswordEdit.text()))
}
data_type = unicode(self.templates[unicode(self.selector.currentText())])
data = data_fields[data_type]
level = (u'L',u'M',u'Q',u'H')
if data:
if data_type == 'emailmessage' and data[1] == '' and data[2] == '':
data_type = 'email'
data = data_fields[data_type]
qr = QR(pixel_size = unicode(self.pixelSize.value()),
data = data,
level = unicode(level[self.ecLevel.currentIndex()]),
margin_size = unicode(self.marginSize.value()),
data_type = data_type,
)
error = 1
if type(fileName) is not unicode:
error = qr.encode()
else:
error = qr.encode(fileName)
if error == 0:
self.qrcode.setPixmap(QtGui.QPixmap(qr.filename))
self.saveButton.setEnabled(True)
else:
if NOTIFY:
n = pynotify.Notification(
"QtQR",
unicode(self.trUtf8("ERROR: Something went wrong while trying to generate the QR Code.")),
"qtqr"
)
n.show()
else:
print "Something went wrong while trying to generate the QR Code"
qr.destroy()
else:
self.saveButton.setEnabled(False)
示例3: get
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
def get(self, path):
home_url = options.home_url
if home_url.startswith("http://"):
home_url = home_url[7:]
q=QR(u""+home_url+"/auth/"+path)
q.encode()
self.set_header("Content-Type", "image/gif")
self.write(open(q.filename).read())
示例4: __init__
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
def __init__(
self, data=u'NULL', pixel_size=3, level='L', margin_size=4, data_type=u'text', filename=None
):
from qrtools import QR
myCode = QR(data=u"Simpledata", pixel_size=10)
myCode.encode()
print myCode.filename
print myCode
示例5: encodeKey
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
def encodeKey(key):
if isinstance(key, str):
int_key = hexToKey(key)
myCode = QR(data="/".join(map(str, int_key)),data_type="text")
myCode.encode()
return myCode.filename
elif isinstance(key, list):
str_key = "/".join(map(str, key))
myIntCode = QR(data=str_key,data_type="text")
myIntCode.encode()
return myIntCode.filename
示例6: qrencode
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
def qrencode(self):
text = [
unicode(self.textEdit.toPlainText()),
unicode(self.urlEdit.text()),
( unicode(self.emailEdit.text()), unicode(self.emailSubjectEdit.text()), unicode(self.emailBodyEdit.toPlainText()) ),
( unicode(self.smsNumberEdit.text()), unicode(self.smsBodyEdit.toPlainText()) ),
unicode(self.telephoneEdit.text()),
]
level = (u'L',u'M',u'Q',u'H')
data_type = (u'text',u'url',u'emailmessage',u'sms',u'telephone')
if text[self.tabs.currentIndex()]:
qr = QR(pixel_size = unicode(self.pixelSize.value()),
data=text[self.tabs.currentIndex()],
level=unicode(level[self.ecLevel.currentIndex()]),
margin_size=unicode(self.marginSize.value()),
data_type=unicode(data_type[self.tabs.currentIndex()]),
)
if qr.encode() == 0:
self.qrcode.setPixmap(QtGui.QPixmap(qr.filename))
self.saveButton.setEnabled(True)
else:
print >>sys.stderr, u"ERROR: Something went wrong while trying to generate de qrcode."
else:
self.saveButton.setEnabled(False)
示例7: _qr_code
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
def _qr_code(qr_code_data):
"""
Create QR code.
@type qr_code_data: string
@param qr_code_data: Data to encode in the qr code
"""
if not qr_code_data:
return "/static/images/default.png"
qr_code_data = "\n".join(qr_code_data)
qr_code_data = "mecard:" + qr_code_data
qr_code = QR(qr_code_data)
qr_code.encode()
with open(qr_code.filename) as filename:
data = filename.read()
return "data:image/png;base64," + data.encode('base64')
qr_code.destroy()
示例8: encodeAES
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
def encodeAES(key, plain, level='L'):
if isinstance(key, str):
int_key = hexToKey(key)
elif isinstance(key, list):
int_key = key[:]
ciphertext = dAES.encrypt(plain, int_key)
if len(ciphertext) > 2952:
print(colors.FAIL+"resulting cipher text is too long ("+str(len(ciphertext))+" characters) to fit in QR code (Even at error correction level L, max length: 2952)"+colors.ENDC)
exit(0)
if not level == 'L':
if level == 'M' and len(ciphertext) > 2330:
print(colors.FAIL+"resulting cipher text is too long ("+str(len(ciphertext))+" characters) to fit in QR code at error correction level M (max length: 2330)"+colors.ENDC)
exit(0)
elif level == 'Q' and len(ciphertext) > 1662:
print(colors.FAIL+"resulting cipher text is too long ("+str(len(ciphertext))+" characters) to fit in QR code at error correction level Q (max length: 1662)"+colors.ENDC)
exit(0)
elif level == 'H' and len(ciphertext) > 1272:
print(colors.FAIL+"resulting cipher text is too long ("+str(len(ciphertext))+" characters) to fit in QR code at error correction level Q (max length: 1662)"+colors.ENDC)
exit(0)
AESqr = QR(data=ciphertext, data_type="text", level=level)
if AESqr.encode() == 0:
return AESqr.filename
else:
print(colors.FAIL+"um..."+colors.ENDC)
示例9: in
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
options['quiet'] = False
options['barWidth'] = 2
# options['isoScale'] = 1
if code not in ('QR', 'qrcode'):
try:
ret_val = createBarcodeDrawing(code, value=str(value), **options)
except Exception, e:
raise osv.except_osv('Error', e)
image_data = ret_val.asString('png')
return base64.encodestring(image_data)
else:
ret_val = False
from qrtools import QR
fd, temp_path = mkstemp(suffix='.png')
qrCode = QR(data=value)
qrCode.encode(temp_path)
fdesc = open(qrCode.filename, "rb")
data = base64.encodestring(fdesc.read())
fdesc.close()
os.close(fd)
os.remove(temp_path)
return data
def generate_image(self, cr, uid, ids, context=None):
"button function for genrating image """
if not context:
context = {}
for self_obj in self.browse(cr, uid, ids, context=context):
image = self.get_image(self_obj.code,
code=self_obj.barcode_type or 'qrcode',
示例10: createBarcodeDrawing
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
options['quiet'] = False
options['barWidth'] = 2
# options['isoScale'] = 1
if code not in ['QR','qrcode']:
try:
ret_val = createBarcodeDrawing(code, value=str(value), **options)
except Exception, e:
raise osv.except_osv('Error', e)
ret_val.save(formats=['svg'], fnRoot='barcode', outDir='/tmp/')
os.system('rsvg-convert %s -o %s' % ('/tmp/barcode.svg', '/tmp/barcode.png'))
return base64.encodestring(open("/tmp/barcode.png","rb").read())
else:
ret_val = False
from qrtools import QR
qrCode = QR(data=value)
qrCode.encode()
return base64.encodestring(open(qrCode.filename,"rb").read())
def generate_image(self, cr, uid, ids, context=None):
"button function for genrating image """
if not context:
context = {}
for self_obj in self.browse(cr, uid, ids, context=context):
image = self.get_image(self_obj.code,
code=self_obj.barcode_type or 'qrcode',
width=self_obj.width, hight=self_obj.hight,
hr=self_obj.hr_form)
self.write(cr, uid, self_obj.id,
{'image':image},context=context)
return True
示例11: range
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
# -*- coding: utf8 -*-
#!/usr/bin/env python
import os
import shutil
import base64
from qrtools import QR
cedula=raw_input("Cedula del profesor para generar el QR: ")
nombre=cedula
for i in range(1,10):
cedula=base64.b64encode(cedula)
code = QR(data=cedula, pixel_size=10)
code.encode()
src = code.get_tmp_file()
dst = '%s/qr/%s.png'%(os.getcwd(),nombre)
shutil.copy(src, dst)
示例12: makeQR
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
def makeQR(self, _data ):
myCode = QR(data=_data, pixel_size=12, level='L')
myCode.encode(QR_IMAGE_FILE)
示例13: qrencode
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
def qrencode(self):
# Functions to get the correct data
data_fields = {
"text": unicode(self.textEdit.toPlainText()),
"url": unicode(self.urlEdit.text()),
"bookmark": (unicode(self.bookmarkTitleEdit.text()), unicode(self.bookmarkUrlEdit.text())),
"email": unicode(self.emailEdit.text()),
"emailmessage": (
unicode(self.emailEdit.text()),
unicode(self.emailSubjectEdit.text()),
unicode(self.emailBodyEdit.toPlainText()),
),
"telephone": unicode(self.telephoneEdit.text()),
"phonebook": (
("N", unicode(self.phonebookNameEdit.text())),
("TEL", unicode(self.phonebookTelEdit.text())),
("EMAIL", unicode(self.phonebookEMailEdit.text())),
("NOTE", unicode(self.phonebookNoteEdit.text())),
("BDAY", unicode(self.phonebookBirthdayEdit.date().toString("yyyyMMdd"))), # YYYYMMDD
(
"ADR",
unicode(self.phonebookAddressEdit.text()),
), # The fields divided by commas (,) denote PO box, room number, house number, city, prefecture, zip code and country, in order.
("URL", unicode(self.phonebookUrlEdit.text())),
# ('NICKNAME', ''),
),
"sms": (unicode(self.smsNumberEdit.text()), unicode(self.smsBodyEdit.toPlainText())),
"mms": (unicode(self.mmsNumberEdit.text()), unicode(self.mmsBodyEdit.toPlainText())),
"geo": (unicode(self.geoLatEdit.text()), unicode(self.geoLongEdit.text())),
}
data_type = unicode(self.templates[unicode(self.selector.currentText())])
data = data_fields[data_type]
level = (u"L", u"M", u"Q", u"H")
if data:
if data_type == "emailmessage" and data[1] == "" and data[2] == "":
data_type = "email"
data = data_fields[data_type]
qr = QR(
pixel_size=unicode(self.pixelSize.value()),
data=data,
level=unicode(level[self.ecLevel.currentIndex()]),
margin_size=unicode(self.marginSize.value()),
data_type=data_type,
)
if qr.encode() == 0:
self.qrcode.setPixmap(QtGui.QPixmap(qr.filename))
self.saveButton.setEnabled(True)
else:
if NOTIFY:
n = pynotify.Notification(
"QtQR",
unicode(self.trUtf8("ERROR: Something went wrong while trying to generate the QR Code.")),
"qtqr",
)
n.show()
else:
print "Something went worng while trying to generate the QR Code"
else:
self.saveButton.setEnabled(False)
示例14: _upload_ws_file
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
def _upload_ws_file(self, cr, uid, ids, fdata=None, context=None):
"""
@params fdata : File.xml codification in base64
"""
if context is None:
context = {}
invoice_obj = self.pool.get('account.invoice')
pac_params_obj = invoice_obj.pool.get('params.pac')
for ir_attachment_facturae_mx_id in self.browse(cr, uid, ids, context=context):
invoice = ir_attachment_facturae_mx_id.invoice_id
comprobante = invoice_obj._get_type_sequence(
cr, uid, [invoice.id], context=context)
cfd_data = base64.decodestring(fdata or invoice_obj.fdata)
xml_res_str = xml.dom.minidom.parseString(cfd_data)
xml_res_addenda = invoice_obj.add_addenta_xml(
cr, uid, xml_res_str, comprobante, context=context)
xml_res_str_addenda = xml_res_addenda.toxml('UTF-8')
xml_res_str_addenda = xml_res_str_addenda.replace(codecs.BOM_UTF8, '')
if tools.config['test_report_directory']:#TODO: Add if test-enabled:
ir_attach_facturae_mx_file_input = ir_attachment_facturae_mx_id.file_input and ir_attachment_facturae_mx_id.file_input or False
fname_suffix = ir_attach_facturae_mx_file_input and ir_attach_facturae_mx_file_input.datas_fname or ''
open( os.path.join(tools.config['test_report_directory'], 'l10n_mx_facturae_pac_finkok' + '_' + \
'before_upload' + '-' + fname_suffix), 'wb+').write( xml_res_str_addenda )
compr = xml_res_addenda.getElementsByTagName(comprobante)[0]
date = compr.attributes['fecha'].value
date_format = datetime.strptime(
date, '%Y-%m-%dT%H:%M:%S').strftime('%Y-%m-%d')
context['date'] = date_format
invoice_ids = [invoice.id]
file = False
msg = ''
cfdi_xml = False
pac_params_ids = pac_params_obj.search(cr, uid, [
('method_type', '=', 'stamp'), (
'company_id', '=', invoice.company_emitter_id.id), (
'active', '=', True)], limit=1, context=context)
if pac_params_ids:
pac_params = pac_params_obj.browse(
cr, uid, pac_params_ids, context)[0]
user = pac_params.user
password = pac_params.password
wsdl_url = pac_params.url_webservice
namespace = pac_params.namespace
## Establece el url del PAC Puede ser demo o producción
url = 'https://facturacion.finkok.com/servicios/soap/stamp.wsdl'
testing_url = 'http://demo-facturacion.finkok.com/servicios/soap/stamp.wsdl'
## Compara si el url establecido es el mismo que el de la configuración del módulo.
if (wsdl_url == url):
url = url
elif (wsdl_url == testing_url):
url = testing_url
else:
raise osv.except_osv(_('Aviso'), _('URL o PAC incorrecto'))
## Verifica si se esta timbrando en webservice Demo
if 'demo' in wsdl_url:
msg += _('¡AVISO, FIRMADO EN MODO PRUEBA!<br/>')
## Conexión
client = Client(url,cache=None)
if True: # if wsdl_client:
file_globals = invoice_obj._get_file_globals(
cr, uid, invoice_ids, context=context)
fname_cer_no_pem = file_globals['fname_cer']
cerCSD = fname_cer_no_pem and base64.encodestring(
open(fname_cer_no_pem, "r").read()) or ''
fname_key_no_pem = file_globals['fname_key']
keyCSD = fname_key_no_pem and base64.encodestring(
open(fname_key_no_pem, "r").read()) or ''
cfdi = base64.encodestring(xml_res_str_addenda)
cfdi = cfdi.replace('\n', '')
## Respuesta del webservice
resultado = client.service.stamp(cfdi,user,password)
htz = int(invoice_obj._get_time_zone(
cr, uid, [ir_attachment_facturae_mx_id.invoice_id.id], context=context))
if resultado['Incidencias']:
# ERROR
codigo_incidencia = resultado['Incidencias'] and \
resultado['Incidencias']['Incidencia'] and \
resultado['Incidencias']['Incidencia'][0]['CodigoError'] or ''
mensaje_incidencia = resultado['Incidencias'] and \
resultado['Incidencias']['Incidencia'] and \
#.........这里部分代码省略.........
示例15: int
# 需要导入模块: from qrtools import QR [as 别名]
# 或者: from qrtools.QR import encode [as 别名]
if album['thumbnail'] != "":
thum = urllib.quote_plus(album['thumbnail'])
thumburl = "%s/image/%s"%(baseurl,thum)
r = requests.get(thumburl, stream=True)
r.raw.decode_content = True # Content-Encoding
try:
im = Image.open(r.raw) #NOTE: it requires pillow 2.8+
basewidth = imgsize[0]
wpercent = (basewidth/float(im.size[0]))
hsize = int((float(im.size[1])*float(wpercent)))
im = im.resize((basewidth,hsize), Image.ANTIALIAS)
background.paste(im, (0,0))
nothumb = False
except:
print "Error opening %s"%thumburl
if nothumb:
font = ImageFont.truetype("Arial.ttf",14)
background=Image.new("RGBA", (500,250),(255,255,255))
draw = ImageDraw.Draw(background)
draw.text((10, 10),album['label'],(0,0,0),font=font)
draw.text((10, 50),', '.join(album['artist']),(0,0,0),font=font)
draw = ImageDraw.Draw(background)
qr = QR(data="%s"%album['albumid'], pixel_size=5)
qr.encode(filename="/tmp/qr.png")
img = Image.open("/tmp/qr.png")
background.paste(img, (background.size[0]-img.size[0],background.size[1]-img.size[1]))
background.save("/tmp/%s.png"%album['albumid'])