mnooner256 / pyqrcode

Python 3 module to generate QR Codes
BSD 3-Clause "New" or "Revised" License
408 stars 74 forks source link

Generate base64 encode png image to use on src in <img> html tag #39

Closed luzfcb closed 8 years ago

luzfcb commented 8 years ago

Hello, first, thanks for this. I need to generate a qr code to be dynamically included in an HTML <img src="data:image/png;base64,......> tag in a Django app.

I would like to avoid any hard disk operation.

This feature already exists somewhere in this library? if not, you can provide me a example of how can I get the code qr encoded in base64 format compatible with browser?

this would be a very useful feature.

Thanks.

goretkin commented 8 years ago

After you install PyPng, you should be able to use the following

import pyqrcode
import io
import base64
c = pyqrcode.create("hello")
s = io.BytesIO()
c.png(s,scale=6)
encoded = base64.b64encode(s.getvalue()).decode("ascii")

If you use IPython Notebook, you can quickly verify if this works for you

from IPython.display import display, HTML
display(HTML('''<img src="data:image/png;base64,''' + encoded + '''">'''))
mnooner256 commented 8 years ago

@Goretkin's solution works. I don't use IPython. I confirmed his solution by writing an html file using the following snippet instead:

with open('test.html', 'w') as f:
    f.write('<html><head></head><body>\n')
    f.write('<img src="data:image/png;base64,{}">\n'.format(encoded))
    f.write('</body></html>')

I then opened the resulting test.html file in Firefox. The expected QR Code was displayed.

Next, I used the save image feature to download the resulting QR Code. The PNG was double checked by running it through a online reader.

Thanks @goretkin for your quick response and fantastic solution!

luzfcb commented 8 years ago

@goretkin Thanks. worked perfectly.

@mnooner256 this is a good example to be in the documentation or as an available as helper function in the core, something like "base64_encoded_png()"

leiradk commented 4 years ago

After you install PyPng, you should be able to use the following

import pyqrcode
import io
import base64
c = pyqrcode.create("hello")
s = io.BytesIO()
c.png(s,scale=6)
encoded = base64.b64encode(s.getvalue()).decode("ascii")

If you use IPython Notebook, you can quickly verify if this works for you

from IPython.display import display, HTML
display(HTML('''<img src="data:image/png;base64,''' + encoded + '''">'''))

After you install PyPng, you should be able to use the following

import pyqrcode
import io
import base64
c = pyqrcode.create("hello")
s = io.BytesIO()
c.png(s,scale=6)
encoded = base64.b64encode(s.getvalue()).decode("ascii")

If you use IPython Notebook, you can quickly verify if this works for you

from IPython.display import display, HTML
display(HTML('''<img src="data:image/png;base64,''' + encoded + '''">'''))

@goretkin This is work for me thanks man. 👍 Your Godblessing