I am using pypng
and pyqrcode
for QR code image generation in django app.
import os from pyqrcode import create import png # pypng import base64 def embed_QR(url_input, name): embedded_qr = create(url_input) embedded_qr.png(name, scale=7) def getQrWithURL(url): name = 'url.png' embed_QR(url, name) with open(name, "rb") as image_file: image_data = base64.b64encode(image_file.read()).decode('utf-8') return image_data
When I call getQrWithURL
with a url, it produces a file url.png
to my directory. Is there a way to only get the image data without producing a file output?
thanks for your help.
Advertisement
Answer
Use a BytesIO
as a writable stream:
import io # Make a writeable stream buffer = io.BytesIO() # Create QR and write to buffer embedded_qr = create(url_input) embedded_qr.png(buffer,scale=7) # Extract buffer contents - this is what you would get by reading a PNG disk file but without creating it PNG = buffer.getvalue()
Your variable PNG
now contains this:
b'x89PNGrnx1anx00x00x00rIHDRx00x00x00xe7x00x00x00xe7x01x00x00x00x00xcdx8f|x8dx00x00x01CIDATxx9cxedx971x92x830x0cExc5PPrx04x8ex92xa3xc1xd1|x14x8ex90x92x82xb1V_2txdexb0;i?cx15qxecGxf3x91xfc%Dxffx89,x8d6xdaxe8x97xf4)x88AWxfbxedxb7Qx93xef'fjx7ftx1fx9exf2Xtxb7xe34x97Cbx9axa43x8axe3XLxfd-xa8xc8x1cx19xbcx11-xbbx1bxd0xa3&mx11xe8xbdxaeX"x1axbex01xa1Qx9aWxaeBEx8fXexeexf4x1cxc44xcdx19nx93dXxfccxb1xcdxc8Lx91Ax08xb5cxd5xcdx1fxeaxb7*xbflxd4xf4x9aoxb8xdeBxbbxd3-cxa4hxbcx9dnxa3xd5xa4tx1dWxdft5x9dtxb1b,Nx88xc8}xe5x93txd4x8aQxa1Ppxbdx06xe43x9fx9dx90x90xfa-xdbxa3xe3bxa2xc0Rw+6n',Ux18Sxdfoxdfxa0xa3x18xf70Jxacxf2xeaxc6xf5xdbxa0xa3%xdc>"x91Rxbdr>zxccHqxcb|Txbax98xfaxa8xe8G1JxcfNxfd[xc3/[xxbbQx04=x8dxfekx16xafnxf1xfcx14mx18BKxefx9axa8xa9xd7xa4'xedxfdx902xd3xf0rx8cx12zxb4xe1x0fWxa1xa2x7fFxa3x8d6xfax15xfdx01xb9MCH#xc3xa2x96x00x00x00x00IENDxaeB`x82'