Python script to generate Meme | Daily Python #11
This article is a tutorial on how to generate a meme using Python and ImgFlip API.
This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.
Requirements:
- Python 3.0
- Pip
Install the following packages:
pip install requests urllib
First, we got to https://imgflip.com/ and create an account
After signing up on ImgFlip, we can use our username and password to communicate with the API. These credentials are required for generating a new meme and not required while fetching the meme templates.
Let’s import the required modules
import requests
import urllib
Now, let’s store all the required credentials into variables
username = 'AjinkyaSonawane'
password = 'dailypy1'
Later we will also require the User-Agent of the browser to save the meme generated, let’s fetch the User-Agent and store it in a variable
userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 \
Safari/537.36'
Let’s fetch the meme templates and list them for the user
#Fetch the available memes
data = requests.get('https://api.imgflip.com/get_memes').json()['data']['memes']
images = [{'name':image['name'],'url':image['url'],'id':image['id']} for image in data]#List all the memes
print('Here is the list of available memes : \n')
ctr = 1
for img in images:
print(ctr,img['name'])
ctr = ctr+1
ctr is a counter used to display as a serial number. It will also be used to fetch the template_id of the selected meme.
Accept the ‘Serial Number’ and Two text fields for the meme
#Take input from user -- Meme, Text0 and Text1
id = int(input('Enter the serial number of the meme : '))
text0 = input('Enter first text : ')
text1 = input('Enter second text : ')
Now that we have the meme template and the required text, let’s generate the meme
#Fetch the generated meme
URL = 'https://api.imgflip.com/caption_image'
params = {
'username':username,
'password':password,
'template_id':images[id-1]['id'],
'text0':text0,
'text1':text1
}
response = requests.request('POST',URL,params=params).json()
print(response)
Let’s save the image using the URL retrieved of the generated meme
#Save the meme
opener = urllib.request.URLopener()
opener.addheader('User-Agent', userAgent)
filename, headers = opener.retrieve(response['data']['url'], images[id-1]['name']+'.jpg')
The image is saved in the current working directory
Generate Memes and share them. I hope this article was helpful, do leave some claps if you liked it.