Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert logo in the center of qrcode in Python?

Tags:

python

qr-code

I am using pyqrcode module in python and generating QR code with it. How to put the logo in the center of that QR code.

The code looks like this

import pyqrcode
data = "Hello World!!"

number = pyqrcode.create(data)
number.png('xyz.png', scale=int(scale))

with open('xyz.png', "rb") as f:
    return HttpResponse(f.read(), content_type="image/png")

Or is there any another way of doing this instead of pyqrcode?

like image 369
Nipun Garg Avatar asked Aug 03 '17 10:08

Nipun Garg


People also ask

Can you put an image in the center of a QR code?

QR Code generators today are becoming more and more complex, and the best part, are mainly free. This means you can very easily come across QR Code generators online that will allow you to build your own QR Code with an embedded image in the middle. This takes away any complexities and often come with templates.


2 Answers

If you use a high-redundancy algorithm (eg H), you can damage the generated QRCode up to a certain percentage. H means you can cover 30% of the data and it'll still work.

That means it's just a case of placing your image over the code. The format is up to you.

enter image description here

import pyqrcode
from PIL import Image
url = pyqrcode.QRCode('http://www.eqxiu.com',error = 'H')
url.png('test.png',scale=10)
im = Image.open('test.png')
im = im.convert("RGBA")
logo = Image.open('logo.png')
box = (135,135,235,235)
im.crop(box)
region = logo
region = region.resize((box[2] - box[0], box[3] - box[1]))
im.paste(region,box)
im.show()
like image 156
L.M Avatar answered Oct 13 '22 00:10

L.M


Though this question is more than 1 year old now, but still I am posting my solution as I got it working hoping that it might help someone else.

CAUTION I generated the qr code image in png format. To get it working, pypng module must be installed.

import pyqrcode
from PIL import Image

# Generate the qr code and save as png
qrobj = pyqrcode.create('https://stackoverflow.com')
with open('test.png', 'wb') as f:
    qrobj.png(f, scale=10)

# Now open that png image to put the logo
img = Image.open('test.png')
width, height = img.size

# How big the logo we want to put in the qr code png
logo_size = 50

# Open the logo image
logo = Image.open('stackoverflow-logo.jpg')

# Calculate xmin, ymin, xmax, ymax to put the logo
xmin = ymin = int((width / 2) - (logo_size / 2))
xmax = ymax = int((width / 2) + (logo_size / 2))

# resize the logo as calculated
logo = logo.resize((xmax - xmin, ymax - ymin))

# put the logo in the qr code
img.paste(logo, (xmin, ymin, xmax, ymax))

img.show()
like image 28
moshfiqur Avatar answered Oct 12 '22 23:10

moshfiqur